0

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');

4
  • 1
    It is passing this, but the code is not using it... Commented Mar 20, 2017 at 16:08
  • 1
    What is fork? Where did you find this example code? Commented Mar 20, 2017 at 16:09
  • @Bergi, I reference from a page, I just want to know the mechanism of using parameter element and index in the function Array.forEach(function(element, index){}). I think the fork() function above is same as forEach(), so, i can understand now. Commented Mar 20, 2017 at 16:54
  • From which page? Please link it! Yes, it works likeforEach. Commented Mar 20, 2017 at 17:02

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your support, I got the idea now: the first this is for specify the context of this in case using of callback function, the second this is just redundant in that case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.