4

How come the code below doesn't work?

var x = {};
x.a = alert;
x.a('asdf'); // TypeError: Illegal invocation
3
  • 2
    The alert function needs is calling context to be window so it can't be called with a different context Commented Feb 24, 2015 at 10:52
  • stackoverflow.com/questions/10743596/… Commented Feb 24, 2015 at 10:53
  • Agree on the duplication but I believe my example is clearer, as is the answer easier to read and understand. (I "knew" this q was posted but didn't find it) Commented Feb 24, 2015 at 11:11

1 Answer 1

2

Because the internals of the alert function requires that the value of this be window.

x.a.call(window,'asdf');

… will work.

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

3 Comments

It looks like window can be replaced with null too(!)
Can you explain it more.
x.a.call(null, 'asdf'); works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.