JS中的原型继承以及如何获取父属性
我试图让属性从父级继承,但我不清楚正确的方法。
可以说我有:
var Animal = function(name){
this.offspring = [];
this.name = name;
return this;
}
Animal.prototype.createOffspring = function(name){
name = name || 'Baby '+(this.offspring.length+1);
this.offspring.push(name);
return this;
}
现在我想添加一个子原型继承,这样我就不必手动添加父级的所有内容。例如,假设我想添加一个基于 Animal
的 Cat
我想这样做,就像它是一个 Animal
var pet = new Cat('Kitty');
pet.createOffspring();
没有必须手动将 name
和 createOffspring
添加到 Cat constructor
中,它实际上只是一个 Animal
,但还有其他一些添加的功能(如 .meow()
或 某物)。
I'm trying to have properties inherit from a parent, but I'm not clear as to the right way of doing it.
Lets say I have:
var Animal = function(name){
this.offspring = [];
this.name = name;
return this;
}
Animal.prototype.createOffspring = function(name){
name = name || 'Baby '+(this.offspring.length+1);
this.offspring.push(name);
return this;
}
Now I want to add a sub prototype inherit so I don't have to manually add everything from the parent. For example, lets say I want to add a Cat
based from Animal
I'd like to do this, like if it were an Animal
var pet = new Cat('Kitty');
pet.createOffspring();
Without manually having to add name
and createOffspring
to the Cat constructor
which is really just an Animal
, but with some other added functionality (like .meow()
or something).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就是这样?
(UPD:原型错误已修复)
(UPD2:抱歉。已经是深夜了,我犯了很多错误..我必须去睡觉)
还有另一种解决方案,但它是 Chrome,FF 特定的(也许是其他):
看起来更短,但不会被诱惑因此:最好遵循 ECMAScript 标准。
That's it?
(UPD: Error with prototype fixed)
(UPD2: Sorry. It is late night, I make a lot of mistakes.. I must go sleep)
There is also another solution, but its Chrome,FF-specific (maybe others):
Looks shorter, but not'd be tempted by this: it's better to follow ECMAScript standart.
正如您在 JavaScript 中所描述的那样,有许多不同的模式用于实现继承,并且它们在处理原型对象的方式方面存在细微的差异。
这里有一些关于原型模式和构造函数模式来帮助您入门。
这是您所描述内容的简单实现。
There are a number of different patterns for implementing inheritance like you're describing in JavaScript, and they have subtle differences as far as how they treat the prototype objects.
Here's are a couple of good references on the prototype pattern and the constructor pattern to get you started.
And here's a simple implementation of what you described.