I have a method that takes a reference to a function and uses that reference to display a data (code below). The problem is that when I use the console.log
function with Google Chrome, an exception occurs, which in this case is as follows:
Uncaught TypeError: Illegal invocation range_methods.foreach (anonymous function)
In Mozilla Firefox, the script runs without any errors. Why is this happening? And how can I modify the script to run in both browsers?
JavaScript:
function Range(from, to) {
'use strict';
var range_obj, range_methods = {
from: from,
to: to,
includes: function (x) {
return this.from <= x && x <= this.to;
},
foreach: function (f) {
var x;
for (x = Math.ceil(this.from) ; x <= this.to; x += 1) {
f(x);
}
},
toString: function () {
return "(" + this.from + "..." + this.to + ")";
}
};
range_obj = Object.create(range_methods);
return range_obj;
}
var r = new Range(1, 3); // Cria um objeto range
r.includes(2); // => true: 2 está no intervalo
r.foreach(console.log); // Exibe 1 2 3
console.log(r); // Exibe (1...3)
Code in JSFiddle (in Google Chrome press Ctrl + Shift + J to see the error in the Console)