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) {
    // ...
}
                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)
                        instanceof is standard, while __proto__ is not (yet - it will most likely be standard in ECMAScript 6).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With