JavaScript prototypal 상속에 관해서 내가 정확히 무엇을했는지 알았습니다. 잔인한 여주인 이네. 다음은 서로 다른 진화가 서로 상속받을 수 있음을 보여주기 위해 Pokemon (예, Pokemon ...)을 사용한 예입니다.Prototypal 상속 및 Object.create
function Squirtle(firstPower) {
this.firstPower = firstPower;
}
Squirtle.prototype.useFirstPower = function() {
console.log("Using " + this.firstPower);
}
function Wartortle(firstPower, secondPower) {
Squirtle.call(this, firstPower);
this.secondPower = secondPower;
}
Wartortle.prototype.useSecondPower = function() {
console.log("Using " + this.secondPower);
}
var mySquirtle = new Squirtle("water squirt");
mySquirtle.useFirstPower(); //works
//squirtle evolved
mySquirtle.prototype = Object.create(Wartortle.prototype);
mySquirtle.useSecondPower(); //no method found
여기서 원하는 효과 Wartortle.prototype
의 prototype
방법 및 Sqruitle.prototype
의 방법을 계속한다. 나는 Wartortle
생성자에서 Squirtle.call(...)
을 사용하여 모든 메소드를 상속받을 수 있다고 가정했습니다. 명백하게. 나는이 재료로 그 어느 때보다 잃어버린 것 같은 기분입니다.
제대로 상속하고 모든 메서드를 슈퍼 및 하위 생성자에서 유지하는 방법 ?? 내가 여기서 뭘 잘못하고 있니?
편집
아래에 언급 한 바와 같이, 내가 new Wartortle
을 사용하여 새 개체를 만들 수 있습니다하지만 난 결국 함께 원래의 객체를 보강되어있는 무슨 생각합니다. 그게 어떻게 작동할까요, 그렇지 않습니까?
그래서''Wartortle' 또는 다른 방법으로 주위에서 상속 mySquirtle'해야합니까? 너는 그걸 섞어 버렸기 때문에. 쓸모없는 객체의'prototype' 속성도 설정하고 있습니다. 왜냐하면 오직 함수 만이 그 속성을 가지고 있기 때문입니다. – basilikum
@basilikum'Wartortle'은'Squirtle'의 진화 된 버전이 될 것입니다 ... 그래서'Wartortle'은'Squirtle'과 같은 방법을 사용해야합니다. – Sethen
하지만 Wartortle의 메서드 인 Squirtle Object 내에서 useSecondPower에 액세스하려고합니까? 또는 생성 된 객체를 Squirtle에서 Wartortle로 변환하는 아이디어입니까? – basilikum