emil
emil

Reputation: 6364

Callback with arrow function in javascript

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.

Upvotes: 2

Views: 4595

Answers (1)

Felix Kling
Felix Kling

Reputation: 816404

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

Upvotes: 3

Related Questions