我想要getter初始化对象的方法
var phas = new Proxy({b:9,
cont:0,
statistic:function(){
console.log(this.cont)
this.cont++
}
}, {
has: function (target, key) {
if (key == "a") return false;
return true;
},
apply: function () {
console.log('run call ')
}
}
)
phas.run();
未捕获的TypeError:phas.run不是函数
答案 0 :(得分:1)
您似乎误解了代理的工作方式。
创建代理时,可以在该对象上创建代理。代理不会自动扩展到对象的属性。
apply
陷阱仅适用于函数,如果代理函数,然后调用它,它将按预期工作。
如果要动态创建方法,则需要执行以下操作:
var p = new Proxy({}, {
get: function(target, prop) {
// If the property exists, just return it
if (prop in target)
return target[prop];
// Otherwise, return a function
return function() { console.log("Some method", prop); };
}
});
p.run() //Logs: Some method run
typeof p.a == 'function' // true