当你做一个instanceof https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#Summary check,
f instanceof Foo
它将需要内部[[prototype]]
对象(可以通过以下方式访问)Object.getPrototypeOf https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf)并查找它是否出现在Foo
的原型链,直到找到Object
沿线。
这里需要注意的另一个重要点是,Foo.prototype
是相同的Bar.prototype
。因为您将同一个对象分配给这两个属性。你可以这样确认
console.log(Foo.prototype === Bar.prototype);
// true
console.log(Object.getPrototypeOf(f) === Object.getPrototypeOf(b));
// true
这就是为什么所有instanceof
您在问题返回中所做的检查true
.
要解决这个问题,您需要创建原型对象,基于EventEmitter
的原型(不带它)。您可以使用Object.create https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create为你做到这一点。它需要一个对象,该对象应该用作新构造对象的原型。
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