0

const button = document.querySelector('button');

button.addEventListener('click', () => {
  console.log('From click listener - arrow function:', this);
});
button.addEventListener('click', function () {
  console.log('From click listener - normal function:', this);
});
Promise.resolve().then(function () { 
  console.log('From Promise - normal function:', this);
});
Promise.resolve().then(() => { 
  console.log('From Promise - arrow function:', this);
});
setTimeout(function () {
  console.log('From setTimeout - normal function:', this);
});
setTimeout(() => {
  console.log('From setTimeout - arrow function:', this);
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<button>Click me!</button>
</body>
</html>

Please have a look at the above code snippet. I'd like to understand how this in inferred in each of the above cases. How is this inside callback functions (eg., the callbacks passed to window.setTimeout, Promise.then, HTMLElement.addEventListener) inferred, in general.

karthikaruna
  • 2,393
  • 5
  • 21
  • 34

1 Answers1

0

If you are writing an arrow function, you'll inherit the this from the outside. If you are writing a "normal" function, you'll create a new context of this.

Doesn't matter if it is a promise, window.setTimeout or any other thing.

For example:

this.value = 2
const example = {
  value: 1,
  arrowFunction: () => this.value,
  normalFunction: function () { return this.value },
}

console.log(example.arrowFunction()) // will print 2
console.log(example.normalFunction()) // will return 1

You can read more about that here: https://www.quora.com/What-does-this-in-JavaScript-mean/answer/Quildreen-Motta

macabeus
  • 3,268
  • 2
  • 28
  • 49