2013-07-17 2 views
0

instanceof 메서드를 검사 할 때 결과가 동일하지 않습니다.javascript 프로토 타입 생성자 및 instanceof

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

먼저 I 위 복귀 trueA

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 상태로, prototype (참조) 속성을 지정.

하지만 B의 constructor을 할당하려고했을 때 결과가 같지 않습니다. false을 반환 carA instanceof B이 경우에

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); 

. 이

답변

1

false를 반환하는 이유는 ... 링크에서 답을 찾을

instanceofhttps://stackoverflow.com/a/12874372/1722625 실제로 왼손 객체의 내부 [[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 B

입니다
관련 문제