2010-02-14 4 views
8

그래서 내가 자바 스크립트와 모든 '프로토 타입의 선 (善)을 배우고, 나는 다음과 같은 이상 난처한 상황에 빠진 오전 :Javascript의 생성자 함수에서 상속하는 생성자 함수를 가져 오는 방법은 무엇입니까?

내가로부터 상속 고양이 생성자 함수를 만들려면 어떻게해야합니까 지금이

var Animal = function (a, b, c, d, e, f, g, h, i, j, k , l, m, n){ 
    this.a = a; 
    this.b = b; 
    //...etc... 
}; 

var x = new Animal(1,2,3....); 

을 말해봐 내가 긴 인수를 다시 입력 할 필요가없는 Animal 생성자 함수? 즉

나는이 일을하지 않으려는 : 사전에

var Cat = function (a, b, c, d, e, f, g, h, i, j, k , l, m, n){ 
    this.a = a; 
    this.b = b; 
    //...etc... 
}; 

// inherit functions if any 
Cat.prototype = new Animal; 

var y = new Cat(1,2,3....); 

감사합니다! j

답변

9

어때요?

var Cat = Function (a, b, c, d, e, f, g, h, i, j, k , l, m, n){ 
    Animal.apply(this, arguments); 
}; 

// inherit functions if any 
Cat.prototype = new Animal; 

var y = new Cat(1,2,3....); 
+0

"인수"대한 추가 정보를 원하시면 여기를 봐 ... 어떤 함수 호출의 범위에 자동적으로 매우 강력한 변수 : http://www.seifi.org/javascript/javascript-arguments.html –

+4

Yuo는 Cat 함수에서 인수 목록 (a, b, c 등)을 선언 할 필요조차 없습니다. 인수에는 여전히 새 Cat (1,2,3 ...) 호출에서 전송 된 값이 포함됩니다. –

+0

감사합니다 Lars! 그게 정확히 내가 찾고 있던 것이 었습니다. – John

1

그것은 신속하게이 같은 매개 변수의 긴 목록의 순서와 의미를 기억하는 지루한된다.

새로운 동물의 속성을 객체로 전달하면 유연성을 추가 할 수 있습니다 ( ). 긴 인수 목록으로 기억하기는 어렵지 않습니다.

function Animal(features){ 
for(var p in features){ 
    this[p]= features[p]; 
} 
}; 

You can give every cat some basic cat features automatically, 
and add specifics when you make a new cat. 

function Cat(features){ 
for(var p in features){ 
    this[p]= features[p]; 
} 
} 
Cat.prototype= new Animal({legs: 4, eats: 'meat', type: 'mammal', whiskers: true}); 
Cat.prototype.constructor=Cat; 

var Tiger= new Cat({tail: true, hunter: true}); 
Tiger begins with these properties: 

tail: true 
hunter: true 
legs: 4 
eats: meat 
type: mammal 
whiskers: true