Matt Huggins
Matt Huggins

Reputation: 83279

Determining a JS object's prototype

What is the best way to determine a JavaScript object's prototype? I am aware of the following two methods, but I'm not sure which is the "best" way (or if there's a better preferred way) in terms of cross-browser support.

if (obj.__proto__ === MY_NAMESPACE.Util.SomeObject.prototype) {
    // ...
}

or

if (obj instanceof MY_NAMESPACE.Util.SomeObject) {
    // ...
}

Upvotes: 4

Views: 83

Answers (2)

apsillers
apsillers

Reputation: 115940

instanceof is prefered. __proto__ is nonstandard -- specifically, it doesn't work in Internet Explorer.

Object.getPrototypeOf(obj) is an ECMAScript 5 function that does the same thing as __proto__.

Note that instanceof searches the whole prototype chain, whereas getPrototypeOf only looks one step up.

Some usage notes:

new String() instanceof String  // true

(new String()).__proto__ == String // false!
                                   // the prototype of String is (new String(""))
Object.getPrototypeOf(new String()) == String // FALSE, same as above

(new String()).__proto__ == String.prototype            // true! (if supported)
Object.getPrototypeOf(new String()) == String.prototype // true! (if supported)

Upvotes: 6

Sean Vieira
Sean Vieira

Reputation: 159905

instanceof is standard, while __proto__ is not (yet - it will most likely be standard in ECMAScript 6).

Upvotes: 3

Related Questions