Joe
Joe

Reputation: 21

call() function in Javascript

I just found the example as follow code, the fork() function may be implement same as the Array.forEach(). So, my question is: why thisp must be passed the fun.call() and why the last argument is this.

Hope to receive your kindly support,

if (!Array.prototype.fork) {
    Array.prototype.fork = function(fun /*, thisp*/ ) {
        var len = this.length;
        //console.log(this);
        if (typeof fun != "function")
            throw new TypeError();

        var thisp = arguments[1];
        console.log(thisp);
        for (var i = 0; i < len; i++) {
            if (i in this)
                fun.call(thisp, this[i], i, this);
        }
    };
}
           
var keywords = ["sdfsdf", "dfhgfh", "Học lập trình", "thehalfheart"]

keywords.fork(function(eachName, index) {
    console.log(index + 1 + ". " + eachName);
}, 'rich');

Upvotes: 0

Views: 91

Answers (1)

gen_Eric
gen_Eric

Reputation: 227240

The 1st parameter to .call() is what the value of this should be inside the called function. The thisp parameter seems to be there in case your callback needs a specific context (this value) to run - such as a method inside a class.

As for why this is passed as the last parameter for call(), that's so your callback can get the original array as a parameter. As you see, you don't need to use it in your callback, but you can.

thisArg = {a:1}
[1,2,3].fork(function(value, index, origArray){
    // origArray will be [1,2,3] in each loop
    // this will be `{a:1}`, because we passed it in as `thisArg`
    // thisArg is optional and will be `null` if not passed
}, thisArg);

For reference, see the docs for forEach: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Upvotes: 1

Related Questions