重新初始化 javascript 对象的属性
在我的 Javascript 拖放构建应用程序中,可以构建各种建筑物。这些具体特征都保存在一个对象中,例如,
var buildings = {
house: ['#07DA21',12,12,0,20],
bank: ['#E7DFF2',16,16,0,3],
stadium: ['#000000',12,12,0,1],
townhall: ['#2082A8',20,8,0,1],
etcetera
}
所以每个建筑物都有许多特征,例如颜色,大小,外观,可以称为建筑物[townhall][0](指颜色)。对象随着用户的改变而改变。然而,当单击“重置”时,整个对象应该再次重置为其初始设置以重新开始,但我不知道该怎么做。对于普通物体来说是这样的。
function building() {}
var building = new building();
delete building;
var building2 = new building();
您可以轻松删除并重新制作它,从而重置属性。但我的对象是自动初始化的。有没有一种方法可以将我的对象变成可以删除和新创建的对象,而不会使事情变得非常复杂,或者有更好的方法来存储这些信息?
In my Javascript drag and drop build app, a variety of buildings can be built. The specific characteristics of these are all saved in one object, like
var buildings = {
house: ['#07DA21',12,12,0,20],
bank: ['#E7DFF2',16,16,0,3],
stadium: ['#000000',12,12,0,1],
townhall: ['#2082A8',20,8,0,1],
etcetera
}
So every building has a number of characteristics, like color, size, look which can be called as buildings[townhall][0] (referring to the color). The object changes as the user changes things. When clicking 'reset' however, the whole object should be reset to its initial settings again to start over, but I have no idea how to do that. For normal objects it is something like.
function building() {}
var building = new building();
delete building;
var building2 = new building();
You can easily delete and remake it, so the properties are reset. But my object is automatically initialized. Is there a way to turn my object into something that can be deleted and newly created, without making it very complicating, or a better way to store this information?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将初始状态保留为对象的原型。
现在,您可以将 a 或 b 的值更改为您想要的任何值。
要恢复,只需使用
您就会恢复初始值。
希望这有帮助。
You can keep initial state as a prototype on an object.
Now, you can change value of a or b to whatever you want.
To restore, just use
You will get your initial value back.
Hope this help.
只需使用复制/克隆方法即可恢复原始状态
现在,只要您需要重置
building
,只需调用reset()
即可。Just use a copy/clone method to restore the original state
Now you can just call
reset()
whenever you need to havebuilding
reset.