Illegal invocation during non configurable method

2019-03-06 01:43发布

问题:

I am using javascript proxies to intercept method calls to an object, however if the method is a non configurable and non writable property, I am not able to correctly intercept it

var handler = {
  get(target, key, receiver) {
      if (target[key] && (typeof target[key] === 'object' || typeof target[key] === "function")) {
      var desc = Object.getOwnPropertyDescriptor(target, key);
      if (desc && ! desc.configurable && !desc.writable) return Reflect.get(target,key);
      var method = Reflect.get(target, key);
      if (typeof method == "function") {
        return function (...args) {
            return method.apply(target, args);
         }
        } else return new Proxy(method, handler);
      } else return Reflect.get(target,key);
    }
 }



var p = new Proxy(window, handler);
p.alert("alert message") // this works fine as I'm passing the correct context inside
                        // `method.apply`
p.location.valueOf(); // throws illegal invocation error as valueOf is a 
                      //non configurable property and I can't pass my custom "function(..args){}" function
                      //as I do for other methods