The following snippet of code is taken from Eloquent JavaScript.
var noCatsAtAll = {};
if ("constructor" in noCatsAtAll)
console.log("Yes, there definitely is a cat called 'constructor'.");
I find it quite mystifying. Why does the ‘if’ return true?
All instances of Object have a
constructorproperty that specifies the function that constructs the Object’s prototype.https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object#Properties_2
The
inoperator looks at all properties, including inherited ones. If you only want to see the properties on the object itself, you can usehasOwnProperty:Note that while the
inoperator sees"constructor", afor (key in a)loop wouldn’t. This is because the"constructor"property is non-enumerable.