概要
インスタンスのプロトタイプを生成した Object 関数への参照を返します。このプロパティの値は関数そのものの参照であり、関数の名前を持った文字列ではないこと、さらにこれが読取専用ではない (1、true、"read-only" のようなプリミティブな真偽値、数値、文字列を除く) ことに注意してください。
| Object のプロパティ | |
| 実装されたバージョン | JavaScript 1.1 |
| ECMAScript エディション | ECMA-262 |
説明
全てのオブジェクトはそれらの prototype から constructor プロパティを継承します。
o = new Object // あるいは JavaScript 1.2 では o = {}
o.constructor == Object
a = new Array // あるいは JavaScript 1.2 では a = []
a.constructor == Array
n = new Number(3)
n.constructor == Number
大部分の HTML オブジェクトはコンストラクタから直接生成できませんが、比較は行うことができます。
document.constructor == Document; document.form3.constructor == Form;
例
例: オブジェクトのコンストラクタを表示する
以下の例は、プロトタイプ Tree と、そのタイプのオブジェクト theTree を生成します。例はその後オブジェクト theTree の constructor プロパティを表示します。
function Tree(name) {
this.name = name;
}
theTree = new Tree("Redwood");
print("theTree.constructor is " + theTree.constructor);
この例は以下のような出力を表示します。
theTree.constructor is function Tree(name) {
this.name = name;
}
例: オブジェクトのコンストラクタを変更する
以下の例は、一般的なオブジェクトのコンストラクタの値を修正する方法を示しています。true、1 と "test" という変数のコンストラクタだけは変更されません。 この例はコンストラクタの関数を信じることが常に安全とは限らないことを説明しています。
function Type() { };
var types = [
new Array, [],
new Boolean, true,
new Date,
new Error,
new Function, function(){},
Math,
new Number, 1,
new Object, {},
new RegExp, /(?:)/,
new String, "test"
];
for(var i = 0; i < types.length; i++){
types[i].constructor = Type;
types[i] = [ types[i].constructor, types[i] instanceof Type, types[i].toString() ];
};
alert( types.join("\n") );
Mozilla Developer Network