如何在javascript中没有proto链的情况下检查instanceof? [英] How can I check instanceof without the proto chain in javascript?

查看:38
本文介绍了如何在javascript中没有proto链的情况下检查instanceof?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在javascript中没有proto链的情况下检查instanceof?

How can I check instanceof without the proto chain in javascript?

var EventEmitter = require('events').EventEmitter;

var Foo = function(){

};
Foo.prototype = EventEmitter.prototype;

var Bar = function(){

};
Bar.prototype = EventEmitter.prototype;

var f = new Foo();
var b = new Bar();

f instanceof Foo; //returns true
b instanceof Bar; //returns true

f instanceof Bar; //returns true
b instanceof Foo; //returns true

本质上,我希望最后两行返回 false.我该怎么做?

Essentially, I want those last two lines to return false. How do I do that?

推荐答案

当你做一个 instanceof 检查,

When you do an instanceof check,

f instanceof Foo

它将采用内部 [[prototype]] 对象(可以通过 Object.getPrototypeOf) 并查找它是否出现在 Foo 原型中的任何地方链,直到它沿线找到Object.

it will take the internal [[prototype]] object (which can be accessed with Object.getPrototypeOf) and find if it occurs anywhere in the Foo's prototype chain, till it finds Object along the line.

这里要注意的另一个重点是,Foo.prototypeBar.prototype 相同.因为您将相同的对象分配给这两个属性.你可以这样确认

Another important point to be noted here is, Foo.prototype is the same as Bar.prototype. Because you assign the same object to both the properties. You can confirm this like this

console.log(Foo.prototype === Bar.prototype);
// true
console.log(Object.getPrototypeOf(f) === Object.getPrototypeOf(b));
// true

这就是您在问题中所做的所有 instanceof 检查都返回 true 的原因.

That is why all the instanceof checks you made in the question return true.

要解决此问题,您需要基于EventEmitter 的原型(而不是使用它)创建原型对象.您可以使用 Object.create 为您做到这一点.它需要一个对象,该对象应该作为新构造对象的原型.

To fix this, you need to create the prototype Objects, based on EventEmitter's prototype (not with it). You can use Object.create to do that for you. It takes an object, which should be used as the prototype of the newly constructed object.

Foo.prototype = Object.create(EventEmitter.prototype);
...
Bar.prototype = Object.create(EventEmitter.prototype);

有了这个变化,

console.log(Foo.prototype === Bar.prototype);
// false
console.log(Object.getPrototypeOf(f) === Object.getPrototypeOf(b));
// false
console.log(f instanceof Foo);
// true
console.log(b instanceof Bar);
// true
console.log(f instanceof Bar);
// false
console.log(b instanceof Foo);
// false

这篇关于如何在javascript中没有proto链的情况下检查instanceof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆