因此,我正在学习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....);提前感谢!J
发布于 2010-02-15 11:07:57
记住像这样的长参数列表的顺序和含义很快就会变得单调乏味。
如果您将新Animal的属性作为对象传递,则可以添加一些灵活性-而且它并不像一长串参数索引那样难以记忆。
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: truehttps://stackoverflow.com/questions/2263353
复制相似问题