所以我正在学习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构造函数的Cat构造函数,这样我就不必再次输入超长参数了?
换句话说,我不想这样做:
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....);
提前致谢! Ĵ
答案 0 :(得分: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....);
答案 1 :(得分: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