Home  >  Q&A  >  body text

javascript - call question

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

PHP中文网PHP中文网2687 days ago676

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-05-19 10:46:24

    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,

    const new_array = arr.map(callback[, thisArg])

    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,

    If this function is in non-strict mode, the this value specified as null and undefined will automatically point to the global object (window object in the browser), and the value of this will be the original value (number, string, Boolean value) An automatic wrapper object that will point to the original value.

    In short, in one sentence, in order to completely simulate the properties of the map function~

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-19 10:46:24

    /q/10...

    reply
    0
  • Cancelreply