Observe the following:
function array_map(array, callback) {
for (var i = 0; i < array.length; i += 1) {
callback(array[i]);
}
}
var a = [], b = [];
array_map([1, 2, 3], function (x) { a.push(x); });
// just gives a = [1, 2, 3] as expected
// but why does this not work: ?
array_map([1, 2, 3], b.push);
// Chrome: a = [], Firefox: can't convert undefined to object
I do understand why this happens, namely: push is no longer bound to b (but to the global object) if you pass it to array_map directly. I don't really understand why Chrome doesn't give an error, at least Firefox seems to give some kind of error.
How can I detect if a function like this is passed to array_map to avoid these kinds of bugs?
I'm hoping there are advanced reflection techniques available to trace the origin of a function. For instance b.push.constructor gives Function, but that's not what I'm looking for.
bindwhen you're calling the function, but inside the function, you can't.