3

我可以设置这样的吸气剂..

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"
4

1 回答 1

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...
于 2013-11-10T14:38:41.500 回答