开发者

Updating a JS object

What I want is to replace the instance attributes in a easy way, and do that inside the class itself. So I can take advantage of the constructor and don't have to create a huge metho开发者_高级运维d just to update.

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)

I guess I am being really naive, is there a good way for it to work doing this sort of context replacement inside the class?


Why not something like:

function update(new_champ) {
    for(var prop in new_champ) {
        if(new_champ.hasOwnProperty(prop) && this.hasOwnProperty(prop)) {
            this[prop] = new_champ[prop];
        }
    }
}

This loops over the properties of the object you pass to the function and updates the corresponding property of the instance only if the instance has such a property.

Btw. you should consider using prototype for creating class methods.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜