我可以像这样设置一个吸气剂..
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"
答案 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...