[英]In JavaScript, how do I inherit from a parent class in child class using a single “.prototype” block?
[英]How do I inherit in JavaScript and specify new prototype members as a single object?
我不喜歡以下內容,因為它多次重復Child.prototype
:
function Parent(a)
{
this.a = a;
}
function Child(a, b)
{
Parent.call(this, a);
this.b = b;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.childValue = 456;
Child.prototype.anotherChildValue = 457;
Child.prototype.yetAnotherValue = 458;
Child.prototype.IHateToWriteChildPrototypeEachTime = 459;
// ...gazillion more Child.prototype.xxx
我想用以下方式指定新成員:
{
constructor: Child,
childValue: 456,
anotherChildValue: 457,
yetAnotherValue: 458,
ILoveThisSinceItsSoTerse: 459,
// ...gazillion more
}
是否有一種不錯的,干凈且有效的方法來執行此操作,而又不創建輔助函數並重新發明輪子呢?
您可以制作一個非常簡單的extend
函數來執行您想要的操作:
var extend = function(obj, methods) {
for(var key in methods) {
if(methods.hasOwnProperty(key)) {
obj[key] = methods[key];
}
}
}
然后您可以說:
extend(Child.prototype, {
constructor: Child,
foo: function() { }
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.