2012-06-18 58 views
2

我正在研究一个JavaScript应用程序,并发现了这种奇怪的行为。
任何人都可以请向我解释为什么JavaScript instanceof运算符返回true时应该是false?

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! 

回答

6

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

相反new BaseClassbase “循环利用” 的,使用方法:

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

这是真的,虽然T.J.克劳德那天回答了一个问题,详细解释了为什么这不一定是最好的做法。我会看看我能否找到它。 – Pointy

+0

+1很好的答案。这是一个非常棘手的问题,并发现我以前已经抓住了! –

+0

@Pointy你的意思是[这一个](http://stackoverflow.com/a/11072626)? –

相关问题