【问题标题】:Determining a JS object's prototype确定 JS 对象的原型
【发布时间】:2013-01-07 18:15:52
【问题描述】:

确定 JavaScript 对象原型的最佳方法是什么?我知道以下两种方法,但就跨浏览器支持而言,我不确定哪种方法是“最佳”方法(或者是否有更好的首选方法)。

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

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

【问题讨论】:

标签: javascript prototype instanceof


【解决方案1】:

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)

【讨论】:

  • 感谢您的信息和示例! :)
【解决方案2】:

instanceof 是标准的,而 __proto__ 不是(尚未 - it will most likely be standard in ECMAScript 6)。

【讨论】:

    猜你喜欢
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2016-09-06
    • 2011-01-14
    相关资源
    最近更新 更多