一个简单的问题,我正在我的控制台中尝试以下操作
let a = new Proxy(new Date(), {})
我希望能够打电话
a.getMonth();
但它不起作用,它抛出:
Uncaught TypeError: this is not a Date object. at Proxy.getMonth (<anonymous>)
at <anonymous>:1:3
有趣的是,在 Chrome 中,自动完成确实会建议 a
上的所有 Date
函数。我错过了什么?
编辑以回应@Bergi
我意识到除了我的问题之外这段代码中有一个错误,但这是我正在尝试做的事情:
class myService {
...
makeProxy(data) {
let that = this;
return new Proxy (data, {
cache: {},
original: {},
get: function(target, name) {
let res = Reflect.get(target, name);
if (!this.original[name]) {
this.original[name] = res;
}
if (res instanceof Object && !(res instanceof Function) && target.hasOwnProperty(name)) {
res = this.cache[name] || (this.cache[name] = that.makeProxy(res));
}
return res;
},
set: function(target, name, value) {
var res = Reflect.set(target, name, value);
that.isDirty = false;
for (var item of Object.keys(this.original))
if (this.original[item] !== target[item]) {
that.isDirty = true;
break;
}
return res;
}
});
}
getData() {
let request = {
...
}
return this._$http(request).then(res => makeProxy(res.data);
}
现在 getData() 返回一些日期
最佳答案
我原来的回答全错了。但是下面的处理程序应该可以工作
const handler = {
get: function(target, name) {
return name in target ?
target[name].bind(target) : undefined
}
};
const p = new Proxy(new Date(), handler);
console.log(p.getMonth());
关于javascript - 日期对象上的代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47874488/