2

我正在开发一个 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!
4

1 回答 1

6

两者都one具有two相同的原型(构造函数BaseClass)。Object.getPrototypeOf(one) === Object.getPrototypeOf(two).

代替“回收” new BaseClassbase使用:

// var base = new BaseClass(); <-- No!
ClassOne.prototype = new BaseClass();
ClassTwo.prototype = new BaseClass();
于 2012-06-18T14:24:24.953 回答