instanceOf函数在JavaScript中的实现

Implementation Of instanceOf function in JavaScript

本文关键字:实现 JavaScript 函数 instanceOf      更新时间:2023-09-26

Stackoverflow大家好!我一直在浏览Mozilla开发者网络的JavaScript指南,并在对象模型的详细信息页面上发现了这个功能:

该函数用于检查对象是否是对象构造函数的实例:

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

还是我遗漏了一点?感谢大家的帮助和提前时间!

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

我知道我有点迟到了,但下面的片段应该和的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
function C() {}
function D() {}
var o = new C();
// true, because: Object.getPrototypeOf(o) === C.prototype
o instanceof C;

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