代码之家  ›  专栏  ›  技术社区  ›  Fabiano Soriani

更新JS对象

  •  0
  • Fabiano Soriani  · 技术社区  · 15 年前

    我想要的是以一种简单的方式替换实例属性,并在类本身内部进行替换。所以我可以利用构造函数,而不必创建一个巨大的方法来进行更新。

    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)
    

    我想我真的很幼稚,有没有一个好的方法让它在类内进行这种上下文替换?

    1 回复  |  直到 15 年前
        1
  •  5
  •   Felix Kling    15 年前

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

    prototype