JavaScript instanceof 运算符何时返回 true 应该为 false?

标签 javascript function new-operator prototype instanceof

我在开发 JavaScript 应用程序时发现了这种奇怪的行为。
谁能给我解释一下原因

function BaseClass() {}
function ClassOne() { this.bar = "foo"; }
function ClassTwo() { this.foo = "bar"; }

var base = new BaseClass();
ClassOne.prototype = base;
ClassTwo.prototype = base;

var one = new ClassOne();
var two = new ClassTwo();
one instanceof ClassTwo && two instanceof ClassOne;
// The line above will return true, but i think it should return false,
// because obviously one is not an instance of ClassTwo!

最佳答案

onetwo 都具有相同的原型(prototype)(构造函数BaseClass)。 Object.getPrototypeOf(一) === Object.getPrototypeOf(二)

不要在 base 中“回收”new BaseClass,而是使用:

// var base = new BaseClass(); <-- No!
ClassOne.prototype = new BaseClass();
ClassTwo.prototype = new BaseClass();

关于JavaScript instanceof 运算符何时返回 true 应该为 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11084799/

相关文章:

javascript - 每 60 秒调用一次函数

python - 如何防止 "AttributeError: '函数'对象没有属性 ''”

c++ - linux 上的运算符 new 和 bad_alloc

javascript - 在对象数组中对动态键进行分组

javascript - rtcpeerconnection 跟踪事件有时返回空流

可以对两种结构类型之一进行操作的 C 函数

c++ - 为什么C++中没有placement delete表达式?

c++ - 下面这句话在c++中是什么意思

javascript - Google Maps JS API 不会在移动设备上加载标记(在桌面上完美运行)

javascript - 如何使用 OData 按部分值进行过滤?