使用JavaScript代理拦截方法调用时非法调用

时间:2018-08-21 22:11:54

标签: javascript javascript-objects es6-proxy

有人可以解释以下输出

var handler = {
  get: function(target,key, receiver){
    return new Proxy(Reflect.get(target, key, receiver),handler);
  }, 
  apply: function(target, thisArg, args){
    Reflect.apply(target, thisArg, args);
  }
}

var p = new Proxy(window, handler);
p.alert("Alert"); // Throws illegal invocation error

var alias = p.alert;
alias("Alert") // Even this works which is baffling for me

var p = new Proxy(Reflect.get(window, "alert"), handler);
p("Alert"); // works as expected

第一个语句抛出非法调用错误,而第二个则没有。他们两个看起来都和我一样,而且我不明白在this

期间第一条语句没有所需的Reflect.apply上下文

1 个答案:

答案 0 :(得分:1)

只是alert需要window作为上下文,否则会引发该错误。它与代理无关。这两个示例抛出相同的错误:

var obj = {};
alert.call(obj, "hello!");           // doesn't work!

和:

var obj = { alert: alert };
obj.alert("hello!");                 // doesn't work!

在您的代码中,如果将p.alert的上下文设置为window,它将起作用:

p.alert.call(window, "hello!");      // works!

var handler = {
  get: function(target, key, receiver) {
    return new Proxy(Reflect.get(target, key, receiver), handler);
  },
  apply: function(target, thisArg, args) {
    Reflect.apply(target, thisArg, args);
  }
}

var p = new Proxy(window, handler);
p.alert.call(window, "Alert");

代码中的其他两个示例可以工作,因为上下文是window