2016-08-10 4 views
1

나는 작은 코드를 가지고 : 코드가 표시Javascript가 constructor.prototype을 사용하여 수퍼 클래스 멤버를 방문하지 못합니까?

function father(){ 
    this.id=10 
} 
function child(){} 
console.log(child.prototype.constructor);//[Function: child] 
child.prototype=new father(); 
//child.prototype.constructor = child; // key line 
var son=new child(); 
console.log(child.prototype.constructor);//[Function: father] 
console.log(son.constructor.prototype.id);//undefined. 

, 나는 "아들"개체를 만들 수 프로토 타입 체인을 사용했다. 그러나 마지막 행은

"undefined". 

이 나에게 이상한 인쇄합니다. child.prototype.constructor는 [Function : father]이고 "id"는 실제로 "father"의 속성이며 왜 정의되지 않은 것을 인쇄합니까? 내가

child.prototype.constructor = child; // key line 

의 keyline 주석을 제거하면 내가 예상대로

는 그런 다음 "10"를 인쇄합니다. 키 라인을 가지고있는 것과 그렇지 않은 것의 차이점은 child.prototype.constructor는 'child'또는 'father'입니다. 그러나 'id'는 아버지 속성이므로 내 코드에 키 라인을 설정해야하는 이유는 무엇입니까?

감사합니다.

+0

'id'는'father' 나'father.prototype'의 속성이 아닙니다. 그것은 '아버지'인스턴스의 속성입니다! – Bergi

+0

나는 나쁜 이미지로 대답하려고 노력했다. :) – Oxi

답변

4

1 단계)

function father(){ 
    this.id=10 
} 
function child(){} 

이 보이는

2 단계) child.prototype=new father();

enter image description here

이제 원래 child.prototype이 손실되고 child.prototype.constructor도 손실, 여기를 참조하십시오. 당신은 father에서 개체를 생성하고 child.prototype

3 단계) var son=new child();

enter image description here

지금 console.log(child.prototype.constructor);//[Function: father] 똑바로 앞으로 이해하기와 같이 객체를 사용했다.

어떻게하면 갈 수 있습니까? son.__proto__.__proto__.constructor. 여기에 어떻게됩니까 같은 이미지

console.log(son.constructor.prototype.id);//undefined. 고려 이제

? son.constructorfather이고 son.constructor.prototypefather.prototype 이외의 문자이며 id은 속성 이름이 없습니다.

참고 : son.constructorchild.prototype.constructor = child; 주석을 무슨 지금 son.__proto__.__proto__.constructor

입니까?

이이 childson.constructor.prototype 의미 son.constructor을 말할 때 당신은 child.prototype 및 그 경우에 constructor 속성을 추가하는 모든 이미지 (10)

죄송 속성 이름 id과 가치를 가지고 child.prototype 아무것도하지만,있다 없다 나쁜 설명 !!

+0

나는 그것을 단어에 넣는 방법을 찾지 못했습니다. 잘 했어. –

+0

좋은 그림. 크기가 축소되지 않았고 초점이 흐려지지 않았 으면 좋겠다. – Season

+0

음, 글쎄, 이건 내가 stackoverflow 여행 이후 내가 가진 최고의 대답 중 하나입니다. 잘 Oxi와 당신의 설명을위한 많은 감사합니다! 투표! – Troskyvs

-1

사실 당신은 자식 기능() 그래서 내부 프로토 연결이 끊어지고의 프로토 타입 객체를 덮어 쓰기한다. console.log(child.prototype.constructor);//[Function: child]을 수행 할 때 당신이 예상대로 작동

enter image description here

이 경우 같은

function father(){ 
    this.id=10 
} 
function child(){} 
console.log(child.prototype.constructor);//[Function: child] 
child.prototype=new father(); 
child.__proto__ = father; 
var son=new child(); 
console.log(child.prototype.constructor);//[Function: father] 
console.log(son.id);//10 
+0

a)'__proto__'를 사용하지 않는다. b) 작동하지 않는다. c) 잃어버린 링크가 없다. – Bergi

+0

그럼 내 질문을 어떻게 설명 할까? 감사. – Troskyvs

+0

__proto__를 직접 사용해서는 안됩니다. __proto__는 Firefox/Chrome에서 제공하는 비표준 속성입니다. 다른 브라우저에서는이 속성이 여전히 내부적으로 존재하지만 숨겨져 있습니다. –