Capture this with an Arrow Function

Marius Schulz
InstructorMarius Schulz
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 6 years ago

Arrow functions are not only syntactically different from other JavaScript functions, but they also have special this behavior. An arrow function doesn't have its own this. Instead, it uses the this value from its enclosing execution context.

When an arrow function is created, it permanently captures the surrounding this value. Neither call() nor apply() can change the this value later. Additionally, arrow functions cannot be used as constructors.

This lesson demonstrates that arrow functions are this-transparent and illustrates how they can solve the problem of incorrect this values within callback functions.

Instructor: [00:00] When it comes to the "this" argument, arrow functions behave differently from function declarations or function expressions. An arrow function does not have its own "this." Instead, it uses the "this" from its enclosing execution context. To demonstrate this behavior, let's store the value of the outer "this" in a variable and then compare it to the inner "this."

[00:31] The "this" binding of an arrow function cannot be set explicitly. If we try to pass a "this" arg to an arrow function using call, apply, or bind, it will be ignored. Put differently, it doesn't matter how we call an arrow function. It's "this" argument will always refer to the "this" value that was captured when the arrow function was created.

[00:52] We also cannot use an arrow function as a constructor. In a constructor, we usually assign properties to "this." It wouldn't make sense to construct an arrow function just to have it assign properties to the "this" of the enclosing execution context.

[01:13] The transparent "this" binding of arrow functions is particularly useful when we want to access "this" within a callback. Consider this Counter object. Let's say we want to increment the count property by one every second. We could use setInterval() and provide a callback which increments this.count.

[01:41] However, if we run this program, we'll see that it doesn't work. The "this" binding within our function expression doesn't refer to our Counter object. It refers to the global object because that's how setInterval() works. We're trying to increment the count property of the global object.

[02:01] Let's convert our function expression to an arrow function. Now, our callback uses the "this" binding from the increment periodically method. Since we invoked increment periodically using the method syntax, "this" is set to counter. Everything works out.