Javascript 更新JS对象
我想要的是以一种简单的方式替换实例属性,并在类本身内部进行替换。所以我可以利用构造函数,而不必创建一个巨大的方法来进行更新Javascript 更新JS对象,javascript,oop,Javascript,Oop,我想要的是以一种简单的方式替换实例属性,并在类本身内部进行替换。所以我可以利用构造函数,而不必创建一个巨大的方法来进行更新 function Champ(champ ){ var instance = this instance.id = champ.id // PERSONAL instance.name = champ.name instance.lore = champ.lore // ATTRIBUTES instance.attr1 = champ.attr
function Champ(champ ){
var instance = this
instance.id = champ.id
// PERSONAL
instance.name = champ.name
instance.lore = champ.lore
// ATTRIBUTES
instance.attr1 = champ.attr1
instance.attr2 = champ.attr2
instance.fitness = champ.fitness
// BARS
instance.energy = champ.energy
instance.stress = champ.stress
function update( new_champ ){
instance = new Champ( new_champ );
}
this.location = "1"
this.update = update
}
// I will put in a simple way, how does it fail for me and how do I wanted it to behave
c = new Champ( {energy: 1, stress : 1} )
c.energy //=> 1 (OK)
c.update( { energy: 9, stress: 9} )
c.energy //=> 1 (FAIL, I wanted it to be 9)
我想我真的很幼稚,有没有一个好的方法可以让它在类中进行这种上下文替换 为什么不做以下事情:
function update(new_champ) {
for(var prop in new_champ) {
if(new_champ.hasOwnProperty(prop) && this.hasOwnProperty(prop)) {
this[prop] = new_champ[prop];
}
}
}
这将循环传递给函数的对象的属性,并仅在实例具有此类属性时更新实例的相应属性
Btw.,您应该考虑使用创建类方法。
为什么不象:function update(new_champ) {
for(var prop in new_champ) {
if(new_champ.hasOwnProperty(prop) && this.hasOwnProperty(prop)) {
this[prop] = new_champ[prop];
}
}
}
这将循环传递给函数的对象的属性,并仅在实例具有此类属性时更新实例的相应属性
Btw.,您应该考虑使用创建类方法。