簡體   English   中英

使用Object.defineProperty定義的屬性的Javascript繼承

[英]Javascript inheritance of properties defined with Object.defineProperty

我有以下父類......

 function Parent(id, name, parameters) { Object.defineProperty(this, "id", { value: id }); Object.defineProperty(this, "name", { value: name, writable: true }); }; 

和相應的子類:

 function Child(id, name, parameters) { Object.defineProperty(this, "phone", { value: parameters.phone, writable: true }); }; 

我嘗試通過添加類似Child.prototype = Object.create(Parent.prototype)的東西來應用繼承; ,但這顯然不起作用。

我如何從Parent類繼承,以便我可以使用屬性id和name。

我嘗試通過添加類似Child.prototype = Object.create(Parent.prototype);東西來應用繼承Child.prototype = Object.create(Parent.prototype);

是的,你應該這樣做,在.prototype對象之間創建一個原型鏈。 你有自己定義的方法,不是嗎?

我如何從Parent類繼承,以便我可以使用屬性id和name。

您基本上需要對Parent構造函數進行“超級”調用,以便它在Child實例上設置您的屬性:

function Child(id, name, parameters) {
  Parent.call(this, id, name, parameters);
  Object.defineProperty(this, "phone", {
    value: parameters.phone,
    writable: true
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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