2013-08-03 1 views
0

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.prototypeprototype 방법 및 Sqruitle.prototype의 방법을 계속한다. 나는 Wartortle 생성자에서 Squirtle.call(...)을 사용하여 모든 메소드를 상속받을 수 있다고 가정했습니다. 명백하게. 나는이 재료로 그 어느 때보다 잃어버린 것 같은 기분입니다.

제대로 상속하고 모든 메서드를 슈퍼 및 하위 생성자에서 유지하는 방법 ?? 내가 여기서 뭘 잘못하고 있니?

편집

아래에 언급 한 바와 같이, 내가 new Wartortle을 사용하여 새 개체를 만들 수 있습니다하지만 난 결국 함께 원래의 객체를 보강되어있는 무슨 생각합니다. 그게 어떻게 작동할까요, 그렇지 않습니까?

+0

그래서''Wartortle' 또는 다른 방법으로 주위에서 상속 mySquirtle'해야합니까? 너는 그걸 섞어 버렸기 때문에. 쓸모없는 객체의'prototype' 속성도 설정하고 있습니다. 왜냐하면 오직 함수 만이 그 속성을 가지고 있기 때문입니다. – basilikum

+0

@basilikum'Wartortle'은'Squirtle'의 진화 된 버전이 될 것입니다 ... 그래서'Wartortle'은'Squirtle'과 같은 방법을 사용해야합니다. – Sethen

+0

하지만 Wartortle의 메서드 인 Squirtle Object 내에서 useSecondPower에 액세스하려고합니까? 또는 생성 된 객체를 Squirtle에서 Wartortle로 변환하는 아이디어입니까? – basilikum

답변

2

이는 방법 "정상"inhertitance의 작품입니다.

1) 변환 함수 쓰기 :

function transform(squirtle, secondPower) { 
    return new Wartortle(squirtle.firstPower, secondPower); 
} 

2) 또는 당신이 꼬부기 개체가하고 wartortle 객체로 변환하려는 경우

이제, 당신은 기본적으로 두 가지 옵션이 있습니다

squirtle.__proto__ = Wartortle.prototype; 
squirtle.secondPower = "awsome secone power"; 

내가 woul : 다른 생성자의 인스턴스가 진정으로 객체를 변경하는 지금까지의 내가있는 유일한 방법을 알고있는 __proto__ 속성을 조작 d는 첫 번째 방법을 고집합니다. 왜냐하면 __proto__은 어디서나 지원되지 않기 때문입니다.

+1

'mySquirtle.prototype'을 단지'Squirtle.prototype'으로 변경하면 실제 예제가 있습니다. – Sethen

+0

편집 한 내용을 앞두고 체크 표시를했습니다 :) – Sethen

+0

아, 감사합니다. :) – basilikum

1

당신의 squirtle을 wartortle로 만들고 싶다면, 새로운 대상을 만들어서는 안됩니까?

mySquirtle = new Wartortle("water squirt", "water gun"); 
mySquirtle.useSecondPower(); 
=> Using water squirt 
=> Using water gun 

편집

가 꼬부기을 변환하려면, 당신은 그것을 개체 자체에 새로운 프로토 타입을 할당하고 두 번째 전원 설정할 수 있습니다

mySquirtle.__proto__ = Wartortle.prototype; 
mySquirtle.secondPower = "water gun"; 

오드 뜨왈렛 2

개체를 변경하는 문제는 프로토 타입이 함수가 아니라 fo가 아니라는 것입니다. r new으로 생성 된 객체. 따라서 Squirtle의 프로토 타입을 변경하려면 모든 새로운 기능을 제공해야합니다.

객체는 프로토 타입에 대한 참조를 가지고 있지만, 프로토 타입 자체가없는 :

console.log(mySquirtle.prototype); 
=> undefined 

그래서 직접 객체에 메소드를 추가 할 수 있습니다,하지만 당신은 객체에 정의 반복 기능이 많이있을 것입니다 하나의 프로토 타입에 정의되는 대신.

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 inherits from Squirtle 
Wartortle.prototype = Object.create(Squirtle.prototype); 
//Wartortle methods 
Wartortle.prototype.useSecondPower = function() { 
    console.log("Using " + this.secondPower); 
} 
var mySquirtle = new Squirtle("water squirt"); 
var myWartortle = new Wartortle("water squirt plus", "ice blast"); 

지금 당신이 꼬부기를 만들 수 있습니다 모든 wartortle 인스턴스가 꼬부기의 메소드를 상속와 별도로 오브젝트 wartortle :

+0

이 작업을 시도했지만이 작업이 진행되는 동안 원래의 개체를 변형하는 것에 대해 궁금합니다. – Sethen

+0

'__proto__'는 파이어 폭스에 특정한 구현체이므로 모든 곳에서 작동하지 않습니다. Node.js를 – Sethen

+0

작품 크롬에 실패하고 난 사파리 확신합니다. – AJcodez

관련 문제