Quick Reference Table
Context |
this Refers To |
Global Scope (Non-Strict Mode) |
window (Browser) / global (Node.js) |
Global Scope (Strict Mode) |
undefined |
Regular Function (Non-Strict Mode) |
window (Browser) / global (Node.js) |
Regular Function (Strict Mode) |
undefined |
Object Method |
The calling object |
Constructor Function |
The new instance |
Class Constructor |
The new instance |
Event Handler (function ) |
The DOM element that received the event |
Event Handler (arrow function ) |
Inherits this from enclosing scope |
Arrow Function |
Inherits this from outer lexical scope |
call() , apply() , bind() |
Explicitly sets this |
Core Concepts
this
is determined by how a function is called, not where it is defined.
- Arrow functions do not have their own
this
; they inherit it from the outer scope.
- Use
.bind()
, .call()
, .apply()
to explicitly set this
.
Global Context
- Non-strict mode →
this
refers to window
(browser) or global
(Node.js).
- Strict mode (
"use strict"
) → this
is undefined
.
console.log(this); // window (browser) | global (Node.js)
"use strict";
console.log(this); // undefined
Function Context
- Non-strict mode →
this
is window
(browser).
- Strict mode →
this
is undefined
.
function showThis() {
console.log(this);
}
showThis(); // window (non-strict) | undefined (strict mode)
Object Method Context
this
refers to the calling object.
const user = {
name: "John",
greet() {
console.log(`Hello, I'm ${this.name}`);
}
};
user.greet(); // "Hello, I'm John"
Constructor & Class Context
- In constructors and classes,
this
refers to the newly created instance.
function User(name) {
this.name = name;
}
const john = new User("John");
console.log(john.name); // "John"