所有属性的Javascript getters / setter

时间:2013-11-10 14:02:17

标签: javascript node.js

我可以像这样设置一个吸气剂..

var o = { get test(){return 'ya'}}
o.test
 ==> "ya"

那么我可以为所有属性和未来创建的属性设置一个全局属性吗?

var o = { get _(){return 'ya'}}
o.test = '1';
o.test
 ==> "ya"
o.moretest = '2';
o.moretest
 ==> "ya"

1 个答案:

答案 0 :(得分:1)

对POJO进行一些轻量级类型检查..无论如何,这对我有用..

$ node --harmony

require('harmony-reflect');

function prox(target) {
  return Proxy(target, {
    get: function(target, name) {
      if(name in target) return target[name];
      throw Error('Not a valid property');
    },
    set: function(target, name, val) {
      if(name in target) return target[name] = val;
      throw Error('Not a valid property');
    }
  });
}

var o = prox({name:'john'});
console.log(o.name);
o.name = 'jo';
console.log(o.name);

o.age = 21;
>> error...