- Advertisement -

- Advertisement -

What is “this” in JavaScript?

0 3

Get real time updates directly on you device, subscribe now.

- Advertisement -

Catching “this” inside an Arrow Function

- Advertisement -

Using this with an arrow function is quite different from using it with any other kind of JavaScript function. An arrow function uses the this value from its enclosing execution context, since it does have one of its own.

An arrow function permanently captures the this value, preventing apply or call from changing it later on.

To explain how this works with regards to the arrow functions, let’s write the arrow function shown below:

const batman = this;
const bruce = () => {
console.log(this === batman);
};
bruce();

Here, we are storing the value of a this in a variable and then comparing the value with a this value that is inside an arrow function. Running node index.js in our terminal should give us true as output.

An arrow function’s this value cannot be set explicitly. Also, the arrow function will ignored any attempt from us at passing a value to this using methods like call, apply, and bind. An arrow function will refer to the this value that was set when the arrow function was created.

An arrow function can also not be used as a constructor. Hence, we cannot assign properties to this inside an arrow function.

So what can arrow functions do in regards to this?

Arrow functions can help us access this within a callback. To explain how this is done. Take a look at the counter object that I have written below:

const counter = {
count: 0,
increase() {
setInterval(function() {
console.log(++this.count);
}, 1000);
}
}
counter.increase();

Running this code using node index.js will only give an increase list of NaNs. This is because this.count is not referring to the counter object. It actually refers to the global object.

To make this counter work, lets rewrite it using an arrow function.

const counter = {
count: 0,
increase () {
setInterval (() => {
console.log (++this.count);
}, 1000);
},
};
counter.increase ();

Our callback now uses this binding from the increase method, and the counter now works as it should.

Note: Do not try to write this.count + 1 instead of ++this.count. The former of these two will only increase the value of count once, and return the that value on each iteration.

- Advertisement -

Get real time updates directly on you device, subscribe now.

- Advertisement -

- Advertisement -

Leave A Reply

Your email address will not be published.

x

We use cookies to give you the best online experience. By agreeing you accept the use of cookies in accordance with our cookie policy.

I accept I decline