簡體   English   中英

如何在JavaScript中繼承並將新的原型成員指定為單個對象?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM