2013-07-17 87 views
0

當我檢查instanceof方法時,結果不一樣。javascript原型構造函數和instanceof

function A(){} 
function B(){}; 

首先我分配prototype(參考)屬性,進A

A.prototype = B.prototype; 
var carA = new A(); 

console.log(B.prototype.constructor); 
console.log(A.prototype.constructor == B); 
console.log(B.prototype.constructor == B); 
console.log(carA instanceof A); 
console.log(carA instanceof B); 

最後4條件對上述返回true

但是,當我試圖指定B的constructor ..結果不一樣。

A.prototype.constructor = B.prototype.constructor; 
var carA = new A(); 

console.log(B.prototype.constructor); 
console.log(A.prototype.constructor == B); 
console.log(B.prototype.constructor == B); 
console.log(carA instanceof A); 
console.log(carA instanceof B); 

在這種情況下carA instanceof B返回false。爲什麼它返回false

回答

1

我找到答案從鏈接.. https://stackoverflow.com/a/12874372/1722625

instanceof實際檢查左側對象的內部[[Prototype]]。同樣像下面

function _instanceof(obj , func) { 
    while(true) { 
     obj = obj.__proto__; // [[prototype]] (hidden) property 
     if(obj == null) return false; 
     if(obj == func.prototype) return true; 
    } 
} 

// which always true 
console.log(_instanceof(carA , B) == (obj instanceof B)) 

如果返回true,objinstanceof