Getter/setter in constructor

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

    You can't do that.

    You can set setter/getters for properties of objects though. I advice you use ES5 Object.defineProperties though. of course this only works in modern browsers.

    var obj = function() {
        ...
        Object.defineProperties(this, {
            "test": {
                 "get": function() { ... },
                 "set": function() { ... }
            }
        });
    }
    
    obj.prototype.func = function() { ... }
    
    var o = new obj;
    o.test;
    o.func();
    

提交回复
热议问题