How does the this keyword work in JavaScript
· Category: JavaScript
Short answer
this refers to the execution context and its value depends on how a function is called, not where it is defined, except for arrow functions which use lexical binding.
Steps
- Implicit binding:
obj.method()setsthistoobj. - Explicit binding:
func.call(context, arg1)andfunc.apply(context, [args])setthisdirectly. - Hard binding:
func.bind(context)returns a new function withthispermanently set. - New binding:
new Constructor()creates a new object and bindsthisto it. - Default binding: In non-strict mode, standalone calls bind
thisto the global object; in strict mode,thisisundefined.
Example
const obj = {
name: 'Eve',
greet() { console.log(this.name); }
};
const fn = obj.greet;
fn(); // undefined (default binding)
obj.greet(); // Eve (implicit binding)
Common issues
- Losing
thiswhen passing methods as callbacks; fix with.bind()or arrow functions. - DOM event handlers default
thisto the element unless using arrow functions.