实现点符号Getter / Setter

时间:2012-06-14 11:57:35

标签: javascript syntax getter-setter

我有一个简单的点符号getter功能,我希望有一个以相同方式工作的setter。有什么想法吗?

var person = {
    name : {
       first : 'Peter',
       last  : 'Smith'
    }
};

// ---

var dotGet = function(str, obj) {

    return str.split('.').reduce(function(obj, i) {
        return obj[i];
    }, obj);

};

var dotSet = function(str, value, obj) {

    // updated, thx to @thg435
    var arr = str.split('.');

    while (arr.length > 1) {
        obj = obj[arr.shift()];
    }

    obj[arr.shift()] = value;

    return obj;

}

// returns `Peter`
var a = dotGet('person.name.first', person);

// should set `person.name.first` to 'Bob'
var b = dotSet('person.name.first', 'Bob', person);

2 个答案:

答案 0 :(得分:3)

var set = function (exp, value, scope) {
  var levels = exp.split('.');
  var max_level = levels.length - 1;
  var target = scope;
  levels.some(function (level, i) {
    if (typeof level === 'undefined') {
      return true;
    }
    if (i === max_level) {
      target[level] = value;
    } else {
      var obj = target[level] || {};
      target[level] = obj;
      target = obj;
    }
  });
};

您可以查看符合您需要的my expression compiler以及更多内容。

用法是:

var scope = {};
set('person.name', 'Josh', scope);

scope.person.name === 'Josh'

答案 1 :(得分:-1)

试试这个:

var dotSet = function(str, value, obj) {
  var keys = str.split('.');
  var parent = obj;

  for (var i = 0; i < keys.length - 1; i++) {
    var key = keys[i];

    if (!(key in parent)) {
      parent[key] = {};
      parent = parent[key];
    }
  }

  parent[keys[keys.length - 1]] = value;
}

var person = {};
dotSet('person.name.first', 'Bob', person);

它产生这个对象:

{person:{name:{first:'Bob'}}}