0

So I was implementing a polyfill for some standards ES6+ methods such as forEach, map reduce

Consider my implementation for map that goes like this :

Array.prototype.myMap = function (callbackFn) {
 var res =[];
 for(var i=0; i<this.length; i++){
   var k = callbackFn(this[i], i);
      res.push(k)
 }
 return res;
 };

Any standard implementation I find on internet would be something like this:

var k = callbackFn.call(this, this[i], i);

For now, Ignore some of the edge cases, for e.g undefined in Sparse array.

But is there a difference if I invoke the callbackFn with call or without call

ABGR
  • 4,631
  • 4
  • 27
  • 49
  • 1
    Yes? It's rather obvious - you'd appoint a value for `this` or not. – VLAZ Sep 26 '22 at 17:36
  • `callbackFn(this[i], i)` is fundamentally different to `callbackFn.call(this[i], i)`. In the former, you're invoking the function with two parameters `this[i]` and `i`. In the latter, you're calling it with a single parameter `i` and setting the value of `this` in the invoked function to be the value of `this[i]` at the call-site. See `thisArg` in the [docs for `call`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) – spender Sep 26 '22 at 17:39
  • Also, a standard implementation should be `callback.call(secondParameterOfTheMapMethod, this[i], i, this)` – VLAZ Sep 26 '22 at 17:41
  • @VLAZ that's right. But if we ignore the `secondParameterOfTheMapFunction` will there still be any difference between the two invokation? Btw I do understand `call` and `apply` and why there are used. – ABGR Sep 26 '22 at 17:42
  • Erm...yes - the value of `this` is still going to be assigned or not. The difference would evidently be if `callback` uses `this` or not. But that's not something you control when writing the code for `myMap`. – VLAZ Sep 26 '22 at 17:44
  • That's interesting. Mind giving an example of this scenario? – ABGR Sep 26 '22 at 17:47
  • 1
    `arr1.map(function(x) { return this.has(x) }, new Set(arr2))` would give you an array of booleans for what is contained in `arr2` or not. https://jsbin.com/vuyimir/1/edit?js,console Or maybe `keys.map(function(x) { return this[x] }, obj)` to map an array of given keys to values from an object. https://jsbin.com/bosebaw/edit?js,console – VLAZ Sep 26 '22 at 17:51

0 Answers0