2

Let's say there are two functions.

function foo(callback) {
...
}

function bar() {
...
}

What's the difference when I call foo(bar) and foo(() => bar()) by assuming bar requires no parameters?

I recently former one occurs error regarding this context, while second one works just fine. I know arrow function binds this context into the function, I have no idea what's the difference.

FYI, here is the code with issue.

socket.disconnect(socket.connect); // line 1

socket.disconnect(() => socket.connect()); // line 2

socket.disconnect(function() { socket.connect(); }); // line 3

I just found that the problem might not be related to the context. It might be something with apply or bind. Because line2 and line 3 works fine, while only line 1 shows error.

emil
  • 6,074
  • 4
  • 30
  • 38
  • 1
    Have you researched the subject of `this`? There is a lot of info on SO which you can find with a simple search... – trincot Nov 04 '17 at 00:33
  • _"I know arrow function binds this context"_, no it doesn't bind any context, `this` will be whatever it was in the outer scope. – Patrick Evans Nov 04 '17 at 00:45
  • "Arrow functions are anonymous and change the way this binds in functions." I read it in a doc. – emil Nov 04 '17 at 00:48
  • Yes in that they don't bind anything in the first place: _"An arrow function does not have its own `this`; the `this` value of the enclosing execution context is used"_ [MDN doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) – Patrick Evans Nov 04 '17 at 00:54
  • @PatrickEvans I just found it's not fat arrow issue... But I am still curious what's the difference – emil Nov 04 '17 at 00:57
  • Possible duplicate of [What does "this" refer to in arrow functions in ES6?](https://stackoverflow.com/questions/28371982/what-does-this-refer-to-in-arrow-functions-in-es6) – Bricky Nov 04 '17 at 01:11

1 Answers1

3

First of all, what you are describing has nothing to do with arrow functions.

The value of this depends on how a function is called. When a function is a property of an object and called as foo.bar(), then this inside foo.bar will refer to foo.

So in your last two examples, this will refer to socket instead socket.connect.

In your first example this will refer to another value because the function won't be executed as method of socket. But socket.connect probably expected to have this referred to socket.


Simplified example:

function foo(callback) {
  callback();
}

var socket = {
  connect() {
    "use strict";
    console.log(this);
  },
};

foo(socket.connect);                  // undefined
foo(() => socket.connect());          // socket object
foo(function() { socket.connect()});  // socket object
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143