2

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

3
  • 1
    For @ibrahimmahrir’s answer as it applies to your proxy, see the error produced by alert.call(new Proxy(window, {}), "alert") Commented Aug 21, 2018 at 22:34
  • 1
    When a function is invoked without an explicit context, the context will be window. Explicit context: in both obj.func and func.call(obj) the context will be obj. Commented Aug 21, 2018 at 22:41
  • @Ry- Thanks for that wonderful example, it actually answers the question. So passing a proxy object of a target as a context is not the same as passing the target itself as the context, which actually makes sense. Commented Aug 22, 2018 at 16:07

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I'll mark this as the answer, but the reason the proxy here becomes relevant is because if I call Reflect.apply inside the get handler itself, this problem no longer occurs, cause now I am calling the method with the target context captured.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.