Getter/setter in constructor

前端 未结 6 1278
清酒与你
清酒与你 2020-12-12 20:43

I recently read about the fact that there is a possibility of defining getters/setters in JavaScript. It seems extremely helpful - the setter is a kind of \'helper\' which c

6条回答
  •  感动是毒
    2020-12-12 21:37

    I know this might be extremely late but I figured out a different way to accomplish what you want and for the sake of people, like myself, googling for an answer to this here it is.

    function Constructor(input){
         this.input = input;
    }
    Object.__defineGetter__.call(Constructor.prototype, "value", function(){
        return this.input * 2;
    });
    
    var test = new Constructor(5);
    alert(test.value) // 10
    

    I've tested this in chrome, safari, mobile safari, firefox and they all work (latest versions of course)

提交回复
热议问题