2013-11-25 7 views
1

개체가 자바 스크립트에서 여러 부모로부터 상속받을 수 있습니까?프로토 타입 상속 및 프로토 타입 속성

Fruit.prototype = new Plant(); 
Fruit.prototype = new anotherPlant(); 

그러나 과일의 프로토 타입 속성 (프로토 타입 객체가) 무슨 설정 얻을 것이다 :

나는 사람이 이런 짓을 했을까 생각하고? 그것이 Fruit의 원래 Parent 생성자 함수의 원래 Parent.prototype일까요?

+0

이것을 확인하십시오. http://stackoverflow.com/questions/9163341/multiple-inheritance-prototypes-in-javascript – PSL

답변

1

수 없습니다. 사실, 많은 언어가 다중 상속을 지원하지 않습니다.

당신이 거기 Plant의 인스턴스에 Fruitprototype을 설정 한 다음 anotherPlant의 인스턴스를 덮어 쓰기됩니다하고있는 모든. 그것은 간단하게 동일합니다;

Fruit.prototype = new anotherPlant(); 

그러나, 자바 스크립트가 상속 체인을 가지고 잊지 마세요. 위의 경우를 사용하여 anotherPlant이 프로토 타입으로 Plant 인 경우 두 객체를 모두 상속받습니다.

function Plant() { 

} 

Plant.prototype.foo = 'foo'; 
Plant.prototype.baz = 'baz-a'; 

function AnotherPlant() { 

} 

AnotherPlant.prototype = new Plant(); 

AnotherPlant.prototype.bar = 'bar'; 
AnotherPlant.prototype.baz = 'baz-b'; 

var a = new AnotherPlant(); 

console.log(a.foo); // foo 
console.log(a.bar); // bar 
console.log(a.baz); // baz-b 

JavaScript는 다른 언어와 다른 방식으로 상속합니다. 프로토 타입 상속을 사용합니다. 즉, 인스턴스를 만드는 데 사용 된 생성자 함수 prototype 속성을 따라 언어가 함수의 상속 체인 (클래스)을 결정한다는 것을 의미합니다.

+0

흠 ... 내가하는 경우에도 매트 Fruit.prototype = new Plant(); Prototype 속성을 Plant.prototype을 가리 키도록 설정하고 있습니다. 따라서 프로토 타입에는 상속 할 프로토 타입 속성을 정의하는 데 사용되는 특성과 부모를 가리키는 프로토 타입 속성이 모두 있습니다. ie 그것의 2 개의 일을하는 동일한 것? – Tomatoes

+0

@Tomatoes : 그렇게하면 식물의'foo'와'baz' 속성을 상속 받게됩니다. 너는 무엇을 기대하고 있니? – Matt

+0

srry 나는 명확하지 않았습니다. 프로토 타입 속성과 프로토 타입 속성을 구별하고 Fruit.prototype = new Plant(); 그것은 영향을 미치는 성명. 이 한 문장이 두 가지 일을 잘 수행하고있는 것 같습니다. 상속 = Plant.prototype 메소드를 상속하고 Plant.prototype을 프로토 타입 객체 (부모 포인터)로 지정합니다. – Tomatoes