确定 JavaScript 对象原型的最佳方法是什么?我知道以下两种方法,但我不确定在跨浏览器支持方面哪个是“最佳”方式(或者是否有更好的首选方式)。
if (obj.__proto__ === MY_NAMESPACE.Util.SomeObject.prototype) {
// ...
}
或者
if (obj instanceof MY_NAMESPACE.Util.SomeObject) {
// ...
}
确定 JavaScript 对象原型的最佳方法是什么?我知道以下两种方法,但我不确定在跨浏览器支持方面哪个是“最佳”方式(或者是否有更好的首选方式)。
if (obj.__proto__ === MY_NAMESPACE.Util.SomeObject.prototype) {
// ...
}
或者
if (obj instanceof MY_NAMESPACE.Util.SomeObject) {
// ...
}
instanceof是首选。__proto__是非标准的——具体来说,它在 Internet Explorer 中不起作用。
Object.getPrototypeOf(obj)是一个 ECMAScript 5 函数,与__proto__.
请注意,instanceof搜索整个原型链,而getPrototypeOf仅向上查找一步。
一些使用说明:
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是标准的,而__proto__不是(目前 -它很可能是 ECMAScript 6 中的标准)。