简体   繁体   中英

Odd javascript behavior for checking “constructor” key in object

I am actually not sure if I just stumbled upon an unwanted behavior in javascript or if this is somehow intended behavior.

The following code results in a true statement:

var test= {"test":1}
document.write("constructor" in test);    

http://jsfiddle.net/xyatxm2g/2/

If I change it to the following code, it returns false as it should:

var test= {"test":1}
document.write(test.hasOwnProperty("constructor"));

http://jsfiddle.net/fg06ovvc/2/

The hasOwnProperty method , as the name says, look into the object to see if it has the property itself.

But when you use 'propertyName' in test , you're not only looking into the object's own properties, but also the properties that come from inheritance.

In that case, constructor is a property that resides inside the Object 's prototype , so all objects have that property, because they all inherit from Object .

Quote from MDN

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator , this method does not check down the object's prototype chain.

From the MDN documentation :

Inherited properties
The in operator returns true for properties in the prototype chain.
"toString" in {}; // returns true

Whereas the hasOwnProperty() method only checks for properties directly on the object, not inherited (ie not on the prototype chain).

Following MDN documentation, it is not an enumerable field.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable

You can perform following test:

var obj = {"t": 23};
obj.propertyIsEnumerable("t")

results: true

obj.propertyIsEnumerable("constructor")

results: false

There is a complete example on this document, under section:

Direct versus inherited properties

I think it may be normal behaviour here that the key in object operator is searching through the prototype chain and returning true for Object.prototype.constructor . See this discussion - it goes over a related topic.

How do I check if an object has a property in JavaScript?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM