0

Hello all I have seen code like the following:

userFunc.apply.bind(userFunc, userFunc)

where userFunc is a function. I don't understand why the first & second arguments to bind are the function itself. What problem does this solve? Isn't the second argument meant for the arguments?

Source code is here.

Boann
  • 48,794
  • 16
  • 117
  • 146
batman
  • 3,565
  • 5
  • 20
  • 41
  • The second argument probably should be something else than `userFunc`. – Bergi Feb 01 '18 at 01:15
  • Where have you seen this code? – Bergi Feb 01 '18 at 01:15
  • `this` is a reference to the scope, because if the callback is called from the function, the scope will be lost. Also, it can be written this way: `userFunc.apply(() => userFunc())`. Also there are lots of similar questions here on this. https://stackoverflow.com/questions/2236747/use-of-the-javascript-bind-method – Xander Luciano Feb 01 '18 at 01:15
  • @XanderLuciano No, `userFunc.apply(() => userFunc())` does something really different than `userFunc.apply.bind(userFunc, userFunc)` – Bergi Feb 01 '18 at 01:19
  • This is not a duplicate guys! @Bergi . I understand its similar, but why this special use case is my question. – batman Feb 01 '18 at 01:21
  • @batman The exact same [explanation](https://stackoverflow.com/a/39907146/1048572) applies. Notice that `userFunc.apply === Function.prototype.apply === Function.apply`, and that the second argument really should have been `null` (or anything else, but not the function itself) as my first comment indicated – Bergi Feb 01 '18 at 01:24
  • @batman Even the use case, as a promise callback, is exactly the same :-) – Bergi Feb 01 '18 at 01:24
  • @Bergi. I have given the source code link stating the second argument is not `null` but rather its own `function` – batman Feb 01 '18 at 01:25
  • @batman Yes, but it does not affect how `apply.bind` works - and ultimately the value is ignored anyway (it's the `this` inside `userFunc`). If you understand what it does, you will see that passing `null` makes more sense than passing `userFunc`. – Bergi Feb 01 '18 at 01:27
  • 1
    @Bergi I just looked at the linked duplicate question and see my mistake. Thanks for the correction. Should have done a little more research before commenting, but better to have to been wrong and learned something, that to have not said anything and be ignorant. Thanks for the correction! – Xander Luciano Feb 02 '18 at 00:36

0 Answers0