Odd JavaScript behavior to validate constructor key in object

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

The following code leads to 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 will return false, as it should:

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

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

+5
source share
4 answers

The hasOwnProperty method, as the name implies, take a look at the object to see if it has its property.

But when you use the 'propertyName' in test , you not only look at the object’s own properties, but also the properties that come from inheritance.

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

Quote from MDN

Each object generated 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 this object; unlike the in operator , this method does not test the prototype of the circuit object.

+9
source

From the MDN documentation :

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

While the hasOwnProperty() method checks for properties directly on the object, rather than being inherited (i.e. not in the prototype chain).

+2
source

Following the MDN documentation, this is not an enumerated field.

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

You can perform the following testing:

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

Results: true

 obj.propertyIsEnumerable("constructor") 

Results: false

This document provides a complete example in the section:

Direct and Inherited Properties

+1
source

I think that there might be normal behavior here, that the key in object operator searches through the prototype chain and returns true for Object.prototype.constructor . See This Discussion - It addresses a related topic.

How to check if an object has a property in JavaScript?

+1
source

Source: https://habr.com/ru/post/1232664/


All Articles