有人可以解释以下输出
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
上下文
答案 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
。