日期对象上的代理

问题描述 投票:3回答:1

简单的问题我在我的控制台中尝试以下操作

let a = new Proxy(new Date(), {})

我期待能够打电话

a.getMonth();

但它不起作用:

未捕获的TypeError:这不是Date对象。在Proxy.getMonth(<anonymous>) 在<匿名>:1:3

有趣的是,在Chrome中自动完成确实建议Date上的所有a功能。我错过了什么?

编辑以回应@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()返回一些日期

javascript ecmascript-6
1个回答
-1
投票

我原来的答案都错了。但是下面的处理程序应该可行

    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());
© www.soinside.com 2019 - 2024. All rights reserved.