2012-02-07 8 views

答えて

5

オブジェクトのすべてのインスタンスには、オブジェクトのプロトタイプを構成する関数を指定するconstructorプロパティがあります。

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object#Properties_2

inオペレータは、継承されたものも含め、すべてのプロパティを調べます。あなただけのオブジェクト自体のプロパティを表示したい場合は、hasOwnPropertyを使用することができます。

var a = {}; 
"constructor" in a; // true 
a.hasOwnProperty("constructor"); // false 

inオペレータが"constructor"を見ながら、for (key in a)ループはないだろう。これは、"constructor"プロパティが列挙できないためです。

2

Objectタイプのコンストラクタです。 constructor関数への参照は、オブジェクトのそのプロパティ(コンストラクタ)で直接使用できます(コンストラクタにも適用されます)。

次に、存在するプロパティの名前はinオブジェクトです。

6

JavaScriptオブジェクトには、オブジェクトのインスタンスを作成した関数であるconstructorという関数があります。すべてのオブジェクトに組み込まれています。 in演算子は、辞書のインスタンスでの何かの存在を "コンストラクタ"とテストしているので、trueを返します。たとえば、lengthをテストした場合も同じことが起こります。

+1

非常に素晴らしい解体。 –

1

constructorは、Objectの方法です。オブジェクトを変更しない限り、すべてのオブジェクトでconstructorメソッドを見つけることができます。 inオペレータは、prototypeチェーンを通じて方法を見つけます。だから、hasOwnPropertyを使用して自分のオブジェクトのプロパティをテストすることをお勧めします。

var noCatsAtAll = {}; 
    if ("constructor" in noCatsAtAll) 
     console.log("Yes, there definitely is a cat called 'constructor'."); 

    if ('constructor' in Object) 
     console.log("Yes, there is also a method called constructor"); 

    var noCon = Object.create(null); // create a completetly empty object 
    console.log('constructor' in noCon); // false 

    function hasConstructorToo() {} 

    console.log('constructor' in hasConstructorToo) // true 
    console.log('constructor' in []); // true 

http://jsfiddle.net/Xsb3E/3 `

関連する問題