19
I have a method that receives a reference to a function and uses that reference to display a data (code below). The problem is that when I use the function console.log
by Google Chrome, there is an exception, which in this case is the following:
Uncaught TypeError: Illegal invocation range_methods.foreach (anonymous function)
Already in Mozilla Firefox the script runs without errors. Why is this happening? And how can I modify the script to run on 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 the Jsfiddle (in Google Chrome press Ctrl + Shift + J to view the error in the Console)