I am reading the book “Secrets of the JavaScript Ninja” by John Resig and in it he is explaining how one can try to anticipate future functionality of the language by extending objects’ prototypes with this code:
if(!Array.prototype.forEach){
Array.prototype.forEach = function(fn, callback){
for(var i = 0; i < this.length; i++){
fn.call(callback || null, this[i], i, this);
}
};
}
Now, I understand that the “callback || null” statement prevents from passing a possible undefined value to the “call” function. What I do not understand is what could be the consequences of passing null as the context of the “fn” parameter. Wouldn’t that make the code crash?
Thank you for any explanation and/or enlightenment you can provide.
No, it won’t cause a crash. According to https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call:
(In the case of a Web-page, “the global object” is
window.)