Home javascript Uncaught TypeError: Illegal invocation

Uncaught TypeError: Illegal invocation

Author

Date

Category

I will repeat the example from Flanagan’s JavaScript manual and get an error in Yandex Browser (read: Chrome):

Uncaught TypeError: Illegal invocation
 Range.foreach /javascript/script.js:11
  (anonymous function)

Safari also has a bug:

TypeError: Type error

However, in Firefox, exactly the same code works. What is this error and how to fix the code?

The actual code:

// Example 9.2. Implementing the Range class with a constructor (Flanagan: 224)
function Range (from, to) {
  this.from = from;
  this.to = to;
}
Range.prototype = {
  foreach: function (f) {
    for (var x = Math.ceil (this.from); x & lt; = this.to; x ++)
      f (x);
  }
};
// An example of using the range object.
var r = new Range (1, 3); // Create a new range object
r.foreach (console.log); // Prints 1 2 3

Answer 1, authority 100%

So try it

r.foreach (function (x) {console.log (x);});

Answer 2, authority 90%

As mentioned here and there .

The console.log function draws attention to the this context, example:

var x = {};
x.func = function () {
  if (this! == x) {
    throw new TypeError ('Illegal invocation');
  }
  console.log ('Hi!');
};
// Works!
x.func ();
var y = x.func;
// TypeError: Illegal invocation
y ();

Accordingly, we will receive an Illegal invocation error. To prevent this from happening, let’s call this function in the context we need:

y.call (x);

Back to the author’s question: in this case, since we are accepting an arbitrary function, it is impossible to define the context inside the foreach method. But, you can bind a context to a function and pass an already associated function like this:

r.foreach (console.log.bind (console));

Answer 3

The console.log chrome function draws attention to the context this , example:

var log = console.log;
log ('cookie');

Accordingly, we will receive an Illegal invocation error. To prevent this from happening, let’s call this function in the console context we need:

log.call (console, 'cookie');

Links:

https://stackoverflow.com/questions/8904782/uncaught-typeerror-illegal -invocation-in-javascript

https://stackoverflow.com/questions/9612398 / chrome-doesnt-recognize-console-log-when-its-called-log

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions