JavaScript: this
JavaScript this refers to a value chosen by the way a function is called.
What you will learn
- How
thisbehaves in methods, constructors, and ordinary functions - Why an arrow function uses
thisfrom its surrounding scope - How strict mode and the runtime environment affect the value
Method context
const user = {
name: "Aki",
greet() {
console.log(this.name);
}
};
user.greet(); // AkiWhen JavaScript evaluates user.greet(), this inside greet refers to user. Calling the same function without its object can produce a different value.
Other common contexts
- Inside a constructor called with
new,thisis the new instance. - In an arrow function,
thisis taken from the surrounding scope; the arrow does not create its own value. - In a strict-mode ordinary function called by itself,
thisisundefined. - In a browser event handler registered as a normal function,
thiscommonly refers to the element receiving the event.
Common mistake
Do not decide what this means from where a function is written. First inspect how it is called, then check whether it is an arrow function, a method, or a constructor.