JS defineProperty and prototype

后端 未结 6 1722
误落风尘
误落风尘 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 09:09

    As you define your properties on the prototype object of all user instances, all those objects will share the same value variable. If that is not what you want, you will need to call defineFields on each user instance separately - in the constructor:

    function User(id, name){
        this.define_fields(["name", "id"]);
        this.id     = id
        this.name   = name
    }
    User.prototype.define_fields = function(fields) {
        var user = this;
        fields.forEach(function(field_name) {
            var value;
            Object.defineProperty(user, field_name, {
                get: function(){ return value; },
                set: function(new_value){
                    /* some business logic goes here */
                    value = new_value;
                }
            });
        });
    };
    

提交回复
热议问题