javascript - call question
PHP中文网
PHP中文网 2017-05-19 10:44:24
0
2
726

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中文网

认证高级PHP讲师

reply all(2)
洪涛

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~

滿天的星座

/q/10...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template