Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
    // ...
}
like image 204
Matt Huggins Avatar asked Jan 14 '23 14:01

Matt Huggins


2 Answers

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)
like image 185
apsillers Avatar answered Jan 25 '23 02:01

apsillers


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

like image 24
Sean Vieira Avatar answered Jan 25 '23 02:01

Sean Vieira