2013-03-18 169 views
1

我只是在玩instanceof操作符。我想知道我的理解是否正確與否javascript實例說明

var C = function(){}; 
// in the above statement C has a "prototype" property which points to an object which has 
// the constructor property which points to C constructor 
var o1 = new C(); 
// in above statement o1.__proto__ is points to C.prototype. that means inheriting from C.prototype. 
console.log(o1 instanceof C) // returns true 
//instanceof will check o1.__proto__ is equals to C.prototype(recursively until it finds null object). 
C.prototype = {}; 
console.log(o1 instanceof C) // false; 
in the above case o1 was inherited from C.prototype which points to the different object not the present C.prototype object (empty object). so the instanceof condition check fails hence its false. 

,請告訴我,如果我的解釋是錯誤的

+1

你的理解似乎是正確的。 – 2013-03-18 20:07:43

回答

3

是,instanceof檢查的對象的原型鏈的構造,並返回true,如果通過構造函數在任何地方都可以找到。所以如果你銷燬一個函數的原型,就像你用一個空的對象覆蓋它一樣,那麼instanceof將總是返回false。