JavaScript에서 프로토 타입 상속을 사용하여 놀았으며 new
키워드의 동작에 혼란스러워했습니다. 상속 된 객체의 [[prototype]]
속성이 Function.prototype
을 가리키는 이유와 상속 된 객체의 프로토 타입이 아닌 이유를 이해할 수 없습니다. 2 개 생성자 (아래) 기능을 고려 : 생성자 함수 Cat
의 프로토 타입을 쿼리자바 스크립트 프로토 타입 상속 및 'new'키워드
function Animal(name) {
this.name = name;
}
function Cat(name) {
Animal.call(this, name);
}
Cat.prototype = new Animal();
을, 나는 몇 가지 흥미로운 결과를 얻을 :
나의 이해는Cat
의
[[prototype]]
는 점에 업데이트해야합니다 것을
Cat.__proto__ === Animal.prototype; //returns false -- shouldn't this be true?
Cat.__proto__ === Function.prototype; //returns true
Cat.prototype instanceof Animal; //returns true, as expected
Animal.prototype
으로 설정하면 프로토 타입 속성이 Animal
의 새 인스턴스로 설정됩니다. 본질적으로는
Animal.prototype
및- 내부적으로 설정된 새 개체를
Cat.[[prototype]]
~Animal
의 외부 프로토 타입 속성을 기반으로 만드시겠습니까?
Chrome과 FF에서 동일한 결과를 얻으려고했습니다. 뭐라 구요?
또한, 때 new Animal()
에Cat.prototype
를 할당 , Cat.prototype
무엇을해야 하는가? 즉 :
//if Cat.prototype = new Animal();
//then
Cat.prototype === Animal.prototype; //get false. Should this be true?
'Cat.prototype = Object.create (Animal.prototype);'- 상속을 설정합니다. –
예, 저는'객체를 알고있었습니다.create()'를 만들지 만 prototypal 상속에 대한 '베어 본 (barebones)'접근 방식을 배우는 것이 목적이었습니다. 'Object.create()'는 다음 단계입니다. –
'prototype' 객체가'Y'의 새로운 인스턴스에 할당 된 프로퍼티로 오염되어'X.prototype = new Y();'에 결함이 있습니다. 이 접근법을 피하고 어떻게해야 하는지를 (Object.create()를 통해)하고 싶을 것이다. –