2013-04-15 3 views
0

내가자바 스크립트 상속

function baseClass(name) { 
    this.name = name; 
    this.getName = function() { 
     return this.name; 
    } 
} 



function subClass(id, company){ 
     baseClass.call(this); 
     this.id = id; 
     this.company = company; 
     this.toString = function() { 
      return name + "\n" + this.id + "\n" + this.company; 
     } 
    } 



subClass.prototype = Object.create(baseClass); 
    var s = new subClass(); 
    s.toString(); //here the name property from the baseClass is not displayed. 

가 제대로 (/ 클래식 원형)

+0

[가능한 중복] (http://stackoverflow.com/questions/16020577/proper-prototypal-inheritance) 45 분 전. 또한 EcmaScript (자바 스크립트)는 프로토 타입 언어이기 때문에 고전을 잊어 버리십시오. – GitaarLAB

+0

"클래식/프로토 타입"- 어느 것을 의미합니까? – Pointy

+0

JavaScript는 ** 프로토 타입 ** 언어이므로 _classical_은 없습니다 ... – War10ck

답변

3

먼저 상속을 구현하려면 어떻게 두 개의 작은 문제가있는 자바 스크립트에서 상속 이해하려고 노력하고 구현 :

  • 케이스를 JavaScript의 문제. Object.create을 소문자로 사용해야하고 함수 이름이 일치하지 않아야합니다 (대 SubClass). 대개 생성자 함수 이름은 대문자입니다.
  • (상속) 재산 this.name를 사용하는 대신 변수 name의 (정의되는)은 - 볼이 제대로 상속

    (방법을 이동 구현하려면 어떻게 Javascript: Do I need to put this.var for every variable in an object?

있는 돈을 프로토 타입 객체에서 생성자 범위에 로컬 변수가 없습니다.) SubClass.prototype은 함수가 아니라 BaseClass.prototype에서 상속받습니다.

function BaseClass(name) { 
    this.name = name; 
} 
BaseClass.prototype.getName = function() { 
    return this.name; 
}; 

function SubClass(id, company){ 
    BaseClass.call(this); 
    this.id = id; 
    this.company = company; 
} 
SubClass.prototype = Object.create(BaseClass.prototype); 
SubClass.prototype.toString = function() { 
    return this.name + "\n" + this.id + "\n" + this.company; 
}; 

new SubClass().toString() 당신은 인수가없는 생성자를 호출하고

BaseClass로

에서 이름 속성을 표시하지 않습니다. id, companyname 속성의 값은 undefined입니다. 또한 SubClass에는 name에 대한 매개 변수도 없으며 BaseClass 생성자 호출에 아무 것도 전달하지 않습니다.

+1

'var s = new SubClass()'도'var s = new subClass()'로 lowercased 할 필요가 있습니다. –

+0

@DavidTansey : 고마워요. – Bergi