簡體   English   中英

如何確保從JavaScript原型繼承的每個對象的唯一ID?

[英]How to ensure a unique ID for each object that inherits from a prototype in JavaScript?

我在JavaScript中有一個類似這樣的構造函數:

var BaseThing = function() {
  this.id = generateGuid();
}

如您所料,當您創建新的BaseThing時,該ID每次都是唯一的。

var thingOne = new BaseThing();
var thingTwo = new BaseThing();
console.log(thingOne.id === thingTwo.id); // false

但是,當我嘗試創建從BaseThing繼承的對象時,事情變得撲朔迷離:

var FancyThing = function() {
   this.fanciness = "considerable";
}
FancyThing.prototype = new BaseThing();

var thingOne = new FancyThing();
var thingTwo = new FancyThing();
console.log(thingOne.id === thingTwo.id); // true

這當然是有道理的,因為原型繼承的工作方式,但這不是我想要的。 我希望ID是唯一的,而不必在繼承自BaseThing的每個對象上重新實現它。

最好的方法是什么? 我唯一能想到的解決方案是(a)在每個子構造函數上重新實現id(但這似乎無法繼承繼承點)或(b)向BaseThing添加某種初始化函數(但我不這樣做)想要擔心確保每次創建事物時都會調用它)。

問題在於您的孩子沒有從父母那里繼承構造函數(函數體)。 您可以先應用父函數,這將產生所需的效果,而不必重寫父中包含的所有內容。 這可以通過使用.apply完成。

 var counter = 0; function generateGuid() { return ++counter; } var BaseThing = function() { this.id = generateGuid(); } var thingOne = new BaseThing(); var thingTwo = new BaseThing(); console.log(thingOne.id === thingTwo.id); // false var FancyThing = function() { BaseThing.apply(this, arguments) // inherit this.fanciness = "considerable"; } FancyThing.prototype = Object.create(BaseThing.prototype, {constructor: {value: FancyThing, writable: true, configurable: true}}); var thingOne = new FancyThing(); var thingTwo = new FancyThing(); console.log(thingOne.id === thingTwo.id); // false 

不幸的是,我不知道從父級擴展而不必以某種方式定義父級被調用的方法。

是的,做相當於調用super的方法也不是壞方法。 您還可以使用電話申請:

function generateGuid(){
    return Math.random(); 
}

var BaseThing = function() {
  this.id = generateGuid();
}

var FancyThing = function() {
   BaseThing.call(this);
   this.fanciness = "considerable";
}


var o = new FancyThing();
console.log(o);

https://repl.it/CYp1/0

您可以通過將id屬性移至BaseThing.prototype並使用Object.defineProperty對其進行“計算”來實現Object.defineProperty

var BaseThing = function() {
  //will define id on prototype
  //this.id = generateGuid();
}

Object.defineProperty(BaseThing.prototype, 'id', {
  configurable: true,
  enumerable: true,
  get: function() {
    //redefine property on first call
    Object.defineProperty(this, 'id', {
        configurable: false,
        enumerable: true,
        value: generateGuid()
    })

    return this.id
  }
})

演示

暫無
暫無

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

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