4

How come the code below doesn't work?

var x = {};
x.a = alert;
x.a('asdf'); // TypeError: Illegal invocation
LosManos
  • 6,117
  • 5
  • 44
  • 81
  • 2
    The alert function needs is calling context to be `window` so it can't be called with a different context – adeneo Feb 24 '15 at 10:52
  • http://stackoverflow.com/questions/10743596/why-are-certain-function-calls-termed-illegal-invocations-in-javascript – Amir Popovich Feb 24 '15 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) – LosManos Feb 24 '15 at 11:11

1 Answers1

2

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

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

… will work.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205