Javascript automatic getter/setters (John Resig Book)

前端 未结 8 646
陌清茗
陌清茗 2020-12-14 03:02

I\'m reading \"Pro Javascript Techniques\" from John Resig, and I\'m confused with an example. This is the code:

// Create a new user object that accepts an          


        
8条回答
  •  天命终不由人
    2020-12-14 03:25

    EDIT: now, adapting Jason's answer, it works:

    We need to make a closure for the values. Here's one way:

    function bindAccessors(o, property, value) {
      var _value = value;
      o["get" + property] = function() {
        return _value;
      };
      o["set" + property] = function(v) {
        _value = v;
      };
    }
    

    Then the User constructor looks like this:

    function User( properties ) {
      for (var i in properties ) {
        bindAccessors(this, i, properties[i]);
      }
    }
    

提交回复
热议问题