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.