Getter/setter in constructor

前端 未结 6 1277
清酒与你
清酒与你 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:40

    @Alex I see it as more option and more power, programming is art, @Nat share his finding with us, and for that I thank him. Maybe someone want to do it that way.

    I'm sure the setter version is the same but just changing that g to a s.

    i.g:

    function Constructor(input){
         this.input = input;
    }
    
    Object.__defineGetter__.call(Constructor.prototype, "value", function(){
        return this.input * 2;
    });
    
    Object.__defineSetter__.call(Constructor.prototype, "bar", function(foo){
        return this.input *= foo;
    });
    
    var test = new Constructor(5);
    console.log(test.value); // 10
    test.bar = 5;
    console.log(test.input); //25
    

    With that said, this feature is deprecated, advices to not to use in production coding.

提交回复
热议问题