2013-03-18 2 views
1

나는 instanceof 연산자로 놀고 있습니다. 나는 나의 이해가 정확한지 여부를 알고 싶어 여부javascript instanceOf 설명

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

귀하의 이해가 맞는 것 같습니다. –

답변

3

예, 객체의 프로토 타입 체인의 생성자를 확인하고 instanceof는 true를 반환하는 경우 전달 된 생성자 체인의 어디에서나 발견됩니다. 따라서 함수의 프로토 타입을 파괴하면 빈 객체로 덮어 쓰듯이 instanceof는 항상 false를 반환합니다.