2016-12-31 1 views
0

빠른 검색을 수행했지만이 질문에 대한 답을 찾을 수없는 것 같습니다. 상속 할 때 함수 프로토 타입을 복사하는 것입니다. this 키워드를 사용하는 대신 생성자 함수 prototype obj에 속성을 추가하는 것이 좋습니다. 그럴만 한 이유가있을 것이라고 확신하지만 자바 스크립트의 뉘앙스를 더 잘 이해하려고 노력하고 있습니다. 예를 들어 정상적인 프로토 타입 상속에서는 "this"라고합니다. 여기프로토 타입 상속과 프로토 타입 객체는이 정도까지 사용되지 않는 이유는 무엇입니까?

let spike=new Dog("Spike",6,"lab"); 

let rover=new Dog("rover",8,"poodle"); 

에 따라 : 당신이 프로토 타입에 properties이있을 때

function Dog(name,age,breed){ 
     this.name=name; 
     this.age=age; 
     this.breed=breed; 
} 
Dog.prototype.bark=function(){console.log("bark bark bark");} 

let spike=new Dog("Spike",6,"lab"); 
let rover=new Dog("Rover",8,"poodle"); 


//^with the constructor function, no instance has the bark function but 
//but refers to the same function on the constructor prototype obj, so the 
//same function isn't being duplicated. However new keyword changes the 
//context of this to refer to the obj so these properties are duplicated 
//on every instance. 

//I'm curious as to the reason why new doesn't change this to refer to the 
//prototype obj for example and then have the instance refers its 
//constructor's prototype like with the bark function? 

//for example why isn't this a common pattern and what are the reasons I 
//should use it. 


function Dog(name,age,breed){ 
     Dog.prototype.name=name; 
     Dog.prototype.age=age; 
     Dog.prototype.breed=breed; 
} 

let spike=new Dog("Spike",6,"lab"); 
let rover=new Dog("rover",8,"poodle"); 


//I feel like the above code would be more DRY, I'm sure there is a reason 
// this isn't common and I'm curious as to why 
+0

'spike.name'이 당신의 방식대로 무엇인지 살펴보고, 왜 사람들이 당신의 방식대로 행동하지 않는지 보게 될 것입니다. – user2357112

답변

3

, 당신은 두 문장에서 아래 새 값으로 속성을 귀하의 예제에서, 즉 클래스의 인스턴스마다 재정의 예상대로 spike.nameSpike이어야하고 rover.namerover이어야합니다. 그러나이 코드를 실행하고 확인하는 경우 모두 rover입니다.

spike의 등록 정보는 rover이라는 새 인스턴스를 만들 때 rover의 등록 정보로 덮어 씁니다. 프로토 타입에 추가 된 methods 또는 properties의 새 인스턴스를 만들 때마다 새 인스턴스를 만들 때마다 새 인스턴스가 생성 될 때마다 하위 클래스에 상속됩니다..

생성자 함수와 새 인스턴스를 만드는 이유는 각 인스턴스에 대해 Spikerover과 같은 속성이 다르기 때문입니다. 메서드의 경우 메서드는 새 인스턴스가 만들어 질 때마다 만들 필요가없는 모든 인스턴스에 대해 다시 사용할 수있는 생성자에 대해 일반적이므로 생성자에서 this 키워드로 정의하는 대신 prototype에 추가합니다 .