fsociety
fsociety

Reputation: 1870

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/

Upvotes: 5

Views: 185

Answers (4)

blackeyebeefhorsefly
blackeyebeefhorsefly

Reputation: 1949

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?

Upvotes: 1

Andre Pastore
Andre Pastore

Reputation: 2907

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

Upvotes: 1

Buzinas
Buzinas

Reputation: 11725

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.

Upvotes: 9

GregL
GregL

Reputation: 38131

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 (i.e. not on the prototype chain).

Upvotes: 2

Related Questions