日期对象上的代理

时间:2017-12-18 18:38:14

标签: javascript ecmascript-6

简单的问题我在我的控制台中尝试以下内容

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

我希望能够致电

a.getMonth();

但它不起作用:

  

未捕获的TypeError:这不是Date对象。       在Proxy.getMonth(< anonymous>)
      在< 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()返回一些日期

1 个答案:

答案 0 :(得分:-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());

相关问题