JS defineProperty and prototype

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

    I came to the same conclusion as Mikhail Kraynov three minutes after he answered. That solution defines new properties each time the constructor is called. I wondered if, as you asked, there was a way of putting the getters and setters in the prototype. Here is what I came up with:

    var User = (function () {
      function User (id, nam) {
        Object.defineProperty (this, '__',  // Define property for field values   
           { value: {} });
    
        this.id = id;
        this.nam = nam;
      }
    
      (function define_fields (fields){
        fields.forEach (function (field_name) {
          Object.defineProperty (User.prototype, field_name, {
            get: function () { return this.__ [field_name]; },
            set: function (new_value) {
                   // some business logic goes here 
                   this.__[field_name] = new_value;
                 }
          });
        });
      }) (fields);
    
      return User;
    }) ();  
    

    In this solution I define the field getters and setters in the prototype but reference a (hidden) property in each instance which holds the field values.

    See the fiddle here : http://jsfiddle.net/Ca7yq

    I added some more code to the fiddle to show some effects on enumeration of properties : http://jsfiddle.net/Ca7yq/1/

提交回复
热议问题