[英]JavaScript instanceof operator returning true when should be false?
I was working on a JavaScript application and came over this weird behavior. 我正在开发一个JavaScript应用程序,并且遇到了这种奇怪的现象。
Can anyone please explain to me why 谁能向我解释为什么
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!
Both one
and two
have the same prototype (constructor BaseClass
). one
和two
都具有相同的原型(构造函数BaseClass
)。 Object.getPrototypeOf(one) === Object.getPrototypeOf(two)
. Object.getPrototypeOf(one) === Object.getPrototypeOf(two)
Instead of "recycling" new BaseClass
in base
, use: 代替在base
中“回收” new BaseClass
,请使用:
// var base = new BaseClass(); <-- No!
ClassOne.prototype = new BaseClass();
ClassTwo.prototype = new BaseClass();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.