我正在构建一个简单的视频游戏,我正在尝试找到从玩家库存数组中删除对象的最佳方法。
我想为每个游戏项目使用一个 ID,但我不确定如何生成这些 ID。
显然,手动为每个实例提供唯一的 ID 效率不高。
我想我可以在构造函数原型(prototype)上添加一个属性,或者直接在构造函数本身上添加一个属性,称为“生成”,该属性随着从中创建的每个实例而增加 1,然后让每个实例返回并使用它作为其 ID 。
或者,我可以在创建每个对象时随机生成一个随机数,但即使数量很大,您可能拥有多个具有相同 ID 的对象的风险也非常小。
如何为每个对象实例添加唯一 ID?
function Item(name,weight,value,description,type){
this.name=name;
this.weight = weight;
this.value=value;
this.description=description;
this.type=type;
this.id= this.generated;/*"this" here obviously means the a property immediately on the object its self on not something further up the chain*/
this.generated+=1;
}
Item.prototype.generated=0;
function Item(name,weight,value,description,type){
this.name=name;
this.weight = weight;
this.value=value;
this.description=description;
this.type=type;
this.id= this.__proto__.constructor.generated;/* this doesnt work either I'm assuming maybe because the constructor and __proto__ properties are added after everything in the constructor function runs, so its undefined?*/
this.__proto__.constructor.generated+=1;
}
Item.generated=0;
最佳答案
使用带有计数器的闭包,每次创建对象时计数器都会递增:
var item=(function(){
var id=0;
return function(name,...){
this.name=name
...
this.id=id;
++id;
}
})()
//to remove an object use Array.splice()
关于javascript - 如何为对象实例生成唯一 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46050664/