Reputation: 44091
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?
Upvotes: 2
Views: 89
Reputation: 11445
constructor
is a method of Object
. You can find the constructor
method throughout all objects unless you modify it. The in
operator will find methods through the prototype
chains. Which is is why it's recommended to use hasOwnProperty
to test for properties in your own objects.
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
Upvotes: 1
Reputation: 68172
All instances of Object have a constructor
property that specifies the function that constructs the Object's prototype.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object#Properties_2
The in
operator looks at all properties, including inherited ones. If you only want to see the properties on the object itself, you can use hasOwnProperty
:
var a = {};
"constructor" in a; // true
a.hasOwnProperty("constructor"); // false
Note that while the in
operator sees "constructor"
, a for (key in a)
loop wouldn't. This is because the "constructor"
property is non-enumerable.
Upvotes: 5
Reputation: 16661
JavaScript objects have a function called constructor
which is the function that created the object's instance. It's built-in to all objects. The in
operator tests for the presence of something called "constructor" in the instance of your dictionary, so it returns true. The same thing would happen if you tested for length
, for example.
Upvotes: 6
Reputation: 285077
It is the constructor of the Object
type. A reference to the constructor
function is available directly on that property ("constructor") of an object (it applies to constructors you write too).
In turn, the names of properties present are in
objects.
Upvotes: 2