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%
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