我在 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
这当然是有道理的,因为原型(prototype)继承的工作方式,但这不是我想要的;我希望 ID 是唯一的,而不必在每个继承自 BaseThing 的对象上重新实现它。
执行此操作的最佳方法是什么?我自己能想到的唯一解决方案是(a)在每个子构造函数上重新实现 id(但这似乎破坏了继承点)或(b)向 BaseThing 添加某种初始化函数(但我不需要担心确保每次创建事物时都调用它)。
最佳答案
问题是您的 child 没有从 parent 那里继承构造函数(函数体)。您可以首先应用父函数,这将产生所需的效果,而不必重写父函数中包含的所有内容。这可以通过使用 .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
不幸的是,我不知道有一种方法可以从父级扩展而不必以某种方式定义父级被调用。
关于javascript - 如何确保从 JavaScript 中的原型(prototype)继承的每个对象的唯一 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37660385/