4

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) {
    // ...
}
2
  • 1
    I would say instanceof because the other method seems a bit hackish, and could easily stop working on the next edition of ECMAScript. Commented Jan 7, 2013 at 18:18
  • 1
    There is a good article that helps you a lot: http://ejohn.org/blog/objectgetprototypeof/ Commented Jan 7, 2013 at 18:23

2 Answers 2

6

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)
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.