constructorプロパティに関するメモ。
constructorプロパティは下記のものがある。
Object.constractorプロパティの働きについて引用する。
constructorプロパティは対象のオブジェクトを生成するために使用されたコンストラクタ関数への参照が代入されています。
Object.prototypeは全てのオブジェクトのプロトタイプなのでどんなオブジェクトもconstrauctorプロパティを持つ。
様々なconstractorプロパティの実行例。
var o = {
hoge: "hoge"
};
o.constructor === Object; // ture
o.constructor; // Object;
// Objectの中身は
// function Object() {
// [native code]
// }
function Foo () {
this.hoge = "hoge";
};
Foo.constructor === Function; // 実行結果 true;
Foo.constructor; // 実行結果 Function ---[1]
// Functionの中身
// function Function() {
// [native code]
// }
function Foo() {
this.hoge = "hoge";
};
var ins = new Foo();
ins.constractor === Foo; // 実行結果 true
ins.constructor; // 実行結果 Foo()
// Foo()の中身
// function Foo() {
// this.hoge = "hoge";
// };
var a = new Array();
a.constructor === Array; // 実行結果 true;
a.constructor; // [ undefined ]
// 配列はオブジェクトではないのでa.constructorはundefined
1. JavaScriptの関数宣言はオブジェクトの定義と生成を同時に行う処理だと言える。そのためfunction Foo () {…}のprototypeはオブジェクトを生成するために使用されたコンストラクタ関数への参照
を表すFunctionになる。
関数が定義されたときに自動的に生成される。初期値はconstructorプロパティのみのオブジェクトのこと。
»constructorとprototype.constructorがわからなくなった – 宇宙野武士は元気にしているか
関数オブジェクトは自分がコンストラクタを想定して定義されたのかを実際にnew演算子で処理されるまで知らない。そのためコンストラクタとして利用されるときのために自身をprototype.constructorプロパティに格納する。
prototype.constructorにはその(関数)オブジェクト自身を持つ
function F () {
this.hoge = "hoge";
};
F.prototype.constructor === F; // 実行結果 true
F.prototype.constructor; // 実行結果 F()
// F()の中身
// function F() {
// this.hoge = "hoge";
// };
function F () {
this.hoge = "hoge";
};
var ins = new F();
ins.prototype.constructor === F; // エラー ---[1]
[1] インスタンス(例ではins)はprototypeプロパティをもたないのでundefined。そのためインスタンス.prototype.constructorはエラーとなる。
詳しくはプロトタイプ・prototype・__proto__ : JavaScriptを参照。
まとめると下記のようになる。
function F() {
this.hoge = "hoge";
};
var ins = new F();
ins.constructor === F.prototype.constructor; // 実行結果 true;
// constructorプロパティの値はF()
// F()の中身は
// function F() {
// this.hoge = "hoge";
// };
No comments yet.
改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。