2014-06-12 6 views
1

자바 스크립트에서 상속에 대해 배우 나는 가상의 상속을 발견했습니다. 여기에 내가 사용하고이 기능 생성자는 다음과 같습니다pseudoclassical 상속을 사용하여 프로토 타입 속성 설정

function MySuperConstructor() { 

} 

MySuperConstructor.prototype = { 
    constructor: MySuperConstructor, 

    myMethod: function() { 
     console.log("method called"); 
    } 

} 

function MyConstructor() { 

} 
내가 혼란 스러워요 것은이 두 방식의 차이입니다

:

MyConstructor.prototype = Object.create(MySuperConstructor.prototype); 

MyConstructor.prototype = MySuperConstructor; 

어떤 차이가 있는가가 ?

+3

두 번째 것은 단순히 완전히 잘못되었습니다. – Bergi

+0

두 번째 것을 어디서 보았습니까? 나는 Bergi와 동의한다. 하나의 유스 케이스를 보지 마라. Child.prototpye = Parent.prototpe를 상속으로 설정한다고하더라도 잘못된 것입니다. Child가 Dog 일 수 있고 Parent가 Animal 일 경우, Dog는 Animal (개는 Animal)과 같지만 Animal은 Dog가 아닙니다. 예를 들어; 당신은 Dog.prototype.bark를 정의 할 것이고 Fish는 Animal에서 상속을 받고 Fish는 껍질을 벗길 수 있습니다. 나는 Object.create를 고집 할 것이다. 자세한 내용은이 대답을 볼 수 있습니다 : http://stackoverflow.com/a/16063711/1641941 – HMR

+0

죄송합니다. 두 번째 구문에서 생성자 앞에 새 키워드가 누락되었습니다 ... 새 구문을 사용하면 두 문장이 동일할까요? – Zed

답변

3

중요한 차이가 있습니다. 함수의 "프로토 타입"속성과 상속에 사용되는 객체의 프로토 타입에 대해 이야기 할 때 혼란을 없애기 위해 객체 프로토 타입 [[Prototype]]을 호출 할 것입니다.

기능의 재산 "프로토 타입"해당 설정을

주 - MyConstructor.prototype = SomeObject하는 new Function를 통해 생성 할 때 객체의 [[Prototype]] 일 무슨 결정

MyObj = new Constructor();하여 MyObj의 [[Prototype]]이 코드에 대한 지금 Constructor.prototype

입니다 :

PrototypeObj = Object.create(MySuperConstructor.prototype); 
MyConstructor.prototype = PrototypeObj; 
MyObj = new MyConstructor(); 

여기에 [[Prototype]] 체인이 있습니다. 두 번째 조각을 대신 사용하는 경우

MyObj -> PrototypeObj -> MySuperConstructor.prototype(the object with myMethod) -> ...

: MyObj 두 번째 경우

MyObj -> MySuperConstructor -> MySuperConstructor's [[Prototype]] (which happens to be Function.prototype) -> ...

, 오브젝트 당신에게 :

여기
MyConstructor.prototype = MySuperConstructor; 
MyObj = new MyConstructor(); 

MyObj에 대한 [[Prototype]] 체인의 정의되고 MySuperConstructor.prototype으로 설정되지 않습니다. MyObj의 프로토 타입 체인에서.

관련 문제