Javascript ES5 Array functions. forEach second “This Value” argument

后端 未结 1 799
一个人的身影
一个人的身影 2021-01-20 09:58

I\'m newbie in Javascript. And I faced the following question.

As stated here, almost all ES5 Array functions (forEach, map, filter, every, some) can take additional

相关标签:
1条回答
  • 2021-01-20 10:22

    It's simple. In the callback function, the this value will be the second argument passed to the array method. If you won't use this, then the argument is irrelevant and you don't need to pass it.

    "use strict";
    [0].forEach(function(currentValue, index, arr) {
      console.log(this); // 1234
    }, 1234);

    Note that in sloppy mode, the this value is converted to an object. So if you omit the argument or use undefined, you will get the global object instead.

    If you need something similar with reduce, then use bind:

    "use strict";
    [0, 1].reduce(function(prevValue, currValue, index, arr) {
      console.log(this); // 1234
    }.bind(1234));

    0 讨论(0)
提交回复
热议问题