【问题标题】:Implementation Of instanceOf function in JavaScriptJavaScript中instanceOf函数的实现
【发布时间】:2012-08-25 14:47:50
【问题描述】:

您好 Stackoverflow 的人们!我一直在浏览 Mozilla 开发者网络的 JavaScript 指南,并在 Details of the object model 页面上遇到了这个功能:

功能是检查一个对象是否是对象构造函数的实例:

function instanceOf(object, constructor) {
   while (object != null) {
      if (object == constructor.prototype)
         return true;
      if (typeof object == 'xml') {
        return constructor.prototype == XML.prototype;
      }
      object = object.__proto__;
   }
   return false;
}

我的问题是,在同一页面上,它说 chrisEngineer 类型的对象,然后以下代码返回 true:

chris.__proto__ == Engineer.prototype;

但是,在上面的instanceOf函数中,它使用下面的比较表达式来检查一个对象是否是一个构造函数的实例:

object == constructor.prototype

表达式不应该是:

object.__proto__ == constructor.prototype

或者我在这里遗漏了一点?提前感谢大家的帮助和时间!

【问题讨论】:

  • 啊哈,谢谢!我认为我在编码上花费了太多时间。休息时间:P
  • 你应该接受正确的答案,而不是仅仅发表评论。
  • @millimoose 答案以前是评论本身。你觉得我会怎么接受?现在我可以并且做到了。

标签: javascript


【解决方案1】:

您在while 循环的底部缺少语句object = object.__proto__;...这将遍历原型链。 object 变量包含该链中每个遍历步骤的当前对象。

【讨论】:

    【解决方案2】:

    我知道我来晚了,但下面是一个 sn-p,它的行为应该与 isInstanceOf 完全一样

    Object.prototype.instanceOf = function (type) {
        let proto = this.__proto__;
        while (proto) {
            if (proto.constructor && proto.constructor === type)
                return true;
            if (proto.__proto__)
                proto = proto.__proto__;
            else
                break;
        }
        return false;
    };
    
    console.log(Number(12).instanceOf(Number));  //true
    

    【讨论】:

      【解决方案3】:
      function C() {}
      function D() {}
      
      var o = new C();
      
      // true, because: Object.getPrototypeOf(o) === C.prototype
      o instanceof C;
      

      instanceOf 将检查左侧对象和右侧对象的原型。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-06
        • 2018-09-25
        相关资源
        最近更新 更多