2

有人可以解释以下输出

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

4

1 回答 1

1

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

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

和:

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

在您的代码中,如果您将上下文设置为p.alertto 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.

于 2018-08-21T22:31:25.197 回答