Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proxy on a date object

Simple question I am trying the following in my console

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

I am expecting to be able to call

a.getMonth();

but it does not work it throws:

Uncaught TypeError: this is not a Date object. at Proxy.getMonth (<anonymous>)
at <anonymous>:1:3

Funny part is that in Chrome the autocomplete does suggest all the Date functions on a. What am I missing?

Edit in response for @Bergi

I realized that there is a bug in this code aside for my question but here is what I am trying to do:

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);
}

Now getData() returns some dates

like image 978
MotKohn Avatar asked Oct 28 '22 21:10

MotKohn


1 Answers

My original answer was all wrong. But the following handler should work

    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());
like image 81
richbai90 Avatar answered Nov 15 '22 06:11

richbai90