instanceOf函数在JavaScript中的实现
Stackoverflow的人们好!我一直在阅读Mozilla开发者网络的JavaScript指南,在页面上看到了这个函数: 该函数用于检查对象是否为对象构造函数的实例:instanceOf函数在JavaScript中的实现,javascript,Javascript,Stackoverflow的人们好!我一直在阅读Mozilla开发者网络的JavaScript指南,在页面上看到了这个函数: 该函数用于检查对象是否为对象构造函数的实例: function instanceOf(object, constructor) { while (object != null) { if (object == constructor.prototype) return true; if (typeof object == '
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;
}
我的问题是,在同一页上,它说ischris
是Engineer
类型的对象,然后以下代码返回true:
chris.__proto__ == Engineer.prototype;
但是,在上述instanceOf
函数中,它使用以下比较表达式检查对象是否是构造函数的实例:
object == constructor.prototype
如果表达式不是:
object.__proto__ == constructor.prototype
还是我遗漏了一点?谢谢大家的帮助和提前的时间 您缺少语句
object=object.\uuuu proto\uuuu代码>位于的底部,而循环。。。这将遍历原型链。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
instanceOf将检查左侧对象和右侧对象的原型。aha,谢谢!我想我花了太多时间在编码上。休息时间:你可能应该接受正确的答案,而不仅仅是评论。@millimoose答案以前是评论本身。你认为我会怎么接受?现在我能做到了。
function C() {}
function D() {}
var o = new C();
// true, because: Object.getPrototypeOf(o) === C.prototype
o instanceof C;