Can someone explain the following output
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
The first statement throws an illegal invocation error, whereas the second one doesn't. Both of them look identical to me, and I don't understand how the first statement doesn't have the required this
context during Reflect.apply
It's just that alert
needs window
as context, otherwise it throws that error. It has nothing to do with proxies. These two examples throw the same error:
var obj = {}; alert.call(obj, "hello!"); // doesn't work!
and:
var obj = { alert: alert }; obj.alert("hello!"); // doesn't work!
In your code if you set the context of p.alert
to window
, it works:
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");
The other two examples from your code work because the context is window
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.