JS defineProperty and prototype

后端 未结 6 1720
误落风尘
误落风尘 2020-12-02 08:15

As you know we can define getters and setters in JS using defineProperty(). I\'ve been stuck when trying to extend my class using defineProperty().

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 08:56

    Please don't implement any other version because it will eat all your memory in your app:

    var Player = function(){this.__gold = 0};
    
    Player.prototype = {
    
        get gold(){
            return this.__gold * 2;
        },
    
    
    
        set gold(gold){
            this.__gold = gold;
        },
    };
    
    var p = new Player();
    p.gold = 2;
    alert(p.gold); // 4
    

    If 10000 objects are instantiated:

    • With my method: you will only have 2 functions in the memory;
    • With the other methods: 10000 * 2 = 20000 functions in the memory;

提交回复
热议问题