In "The Definitive Guide to JavaScript" there is a function used to implement Array.prototype.map
:
var map = function(a,f){
var results = [];
for(var i = 0,l = a.length; i<l; i++){
if(i in a){
results[i] = f.call(null,a[i],i,a);//这里
}
}
return results;
};
Why use call(null)
instead of using f(a[i], i, a)
directly? In this way, this points to the global situation
You can see that the map implemented here is in this form, that is, map(array, f), which can only be called with two parameters.
Let’s take a look at the function prototype given on MDN again,
callback is what we call f, so the last this is optional, and the function provided in the book does not consider this value at all, then when this value is not passed, If the thisArg parameter is omitted, or the value is assigned If it is null or undefined, this points to the global object.
In addition, we know that when using the function object call method,
In short, in one sentence, in order to completely simulate the properties of the map function~
/q/10...