What does "this" mean in JavaScript?
Short answer
In a regular function, this is determined at call time by what precedes the dot. Arrow functions have no this of their own and inherit it from the enclosing scope.
const user = {
name: 'Dom',
greet() {
return `Hi, ${this.name}`;
},
};
user.greet(); // 'Hi, Dom' — called on user
const fn = user.greet;
fn(); // 'Hi, undefined' — no object before the dotThe method did not change. The call did. That is the entire concept.
#The classic callback bug
button.addEventListener('click', user.greet); // this is the button, not userFixes:
button.addEventListener('click', () => user.greet());
button.addEventListener('click', user.greet.bind(user));#Arrow functions capture this
class Timer {
constructor() {
this.seconds = 0;
setInterval(() => { this.seconds++; }, 1000); // works
}
}With a regular function there, this would be the timer object or undefined. Arrow functions inherit this from where they were written, which is what you want in a callback.
#Which is why arrows are wrong for methods
const user = {
name: 'Dom',
greet: () => `Hi, ${this.name}`, // this is NOT user
};Defined at the top level of a module, this is undefined. Use shorthand method syntax for object methods.
#The rules, in priority order
new Foo()—thisis the new object.fn.call(obj),fn.apply(obj),fn.bind(obj)—thisisobj.obj.fn()—thisisobj.- Plain
fn()—undefinedin strict mode and modules,globalThisotherwise. - Arrow function — whatever
thiswas where it was defined.