ddjk
ddjk

Reputation: 133

Why does [1,2,3].prototype === Array.prototype return false?

I am playing with Prototype in my Chrome console. Wouldn't [1,2,3].prototype === Array.prototype equate to the same prototype since they both contain the same methods?

Upvotes: 0

Views: 59

Answers (3)

Mark Reed
Mark Reed

Reputation: 95252

Non-Class objects don't have a prototype property. They instead have __proto__. So this works:

[1,2,3].__proto__ == Array.prototype
//=> true

But it's deprecated. If you really need to explicitly check the prototype, you can use this in modern JS engines:

Object.getPrototypeOf([1,2,3]) == Array.prototype

In general, however, the way to check if an object is an instance of a class is to use instanceof:

[1,2,3] instanceof Array
//=> true

Upvotes: 4

Qiu Zhou
Qiu Zhou

Reputation: 1275

Add some extra points that deserves attention, __proto__ is an internal property that is not encouraged to use, and only need to be implemented in browser environment according to language specification, Object.getPrototypeOf() is better.

Also you can do it by isPrototypeOf:

Array.prototype.isPrototypeOf([1,2,3])

Upvotes: 1

Jaromanda X
Jaromanda X

Reputation: 1

Older javascript engines (and current, but is considered deprecated)

[1,2,3].__proto__ === Array.prototype

Modern javascript engines (i.e. not IE)

Object.getPrototypeOf([1,2,3]) === Array.prototype

Upvotes: 3

Related Questions