Visit Mozilla.org

Core JavaScript 1.5 Reference:Global Objects:Object:constructor

出典: MDC


目次

[編集] 概要

インスタンスのプロトタイプをを生成した Object 関数への参照を返します。このプロパティの値は関数そのものの参照であり、関数の名前を持った文字列ではないこと、さらにこれが読み取り専用ではない (1、true、"read-only" のようなプリミティブな真偽値、数値、文字列を除く) ことに注意してください。

Object のプロパティ
実装されたバージョン: JavaScript 1.1, NES2.0
ECMA バージョン: 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 を生成します。例はその後オブジェクト theTreeconstructor プロパティを表示します。

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"));