how to use javascript Object.defineProperty

前端 未结 10 1186
不知归路
不知归路 2020-11-29 14:21

I looked around for how to use the Object.defineProperty method, but couldn\'t find anything decent.

Someone gave me this snippet of code:

Object.def         


        
10条回答
  •  一向
    一向 (楼主)
    2020-11-29 14:57

    get is a function that is called when you try to read the value player.health, like in:

    console.log(player.health);
    

    It's effectively not much different than:

    player.getHealth = function(){
      return 10 + this.level*15;
    }
    console.log(player.getHealth());
    

    The opposite of get is set, which would be used when you assign to the value. Since there is no setter, it seems that assigning to the player's health is not intended:

    player.health = 5; // Doesn't do anything, since there is no set function defined
    

    A very simple example:

    var player = {
      level: 5
    };
    
    Object.defineProperty(player, "health", {
      get: function() {
        return 10 + (player.level * 15);
      }
    });
    
    console.log(player.health); // 85
    player.level++;
    console.log(player.health); // 100
    
    player.health = 5; // Does nothing
    console.log(player.health); // 100

提交回复
热议问题