Understanding `this`
10 min read
The `this` Keyword
this refers to the execution context — the object that is currently calling the function. Its value is determined at call time, not at definition time (except for arrow functions, which inherit this from their lexical scope).
javascript
// Method call — this = the object before the dot
const obj = {
name: "Alice",
greet() {
console.log("Hi, I am " + this.name);
}
};
obj.greet(); // "Hi, I am Alice"
// Detached call — this = undefined (strict) or globalThis
const fn = obj.greet;
fn(); // "Hi, I am undefined" (or TypeError in strict mode)Explicit Binding: call, apply, bind
javascript
function introduce(greeting, punctuation) {
console.log(greeting + ", I am " + this.name + punctuation);
}
const person = { name: "Bob" };
introduce.call(person, "Hello", "!"); // Hello, I am Bob!
introduce.apply(person, ["Hi", "."] ); // Hi, I am Bob.
const boundFn = introduce.bind(person, "Hey");
boundFn("~"); // Hey, I am Bob~Arrow Functions and this
javascript
class Timer {
constructor() {
this.seconds = 0;
}
start() {
// Arrow function captures `this` from start()
setInterval(() => {
this.seconds++;
console.log(this.seconds);
}, 1000);
}
}
new Timer().start(); // 1, 2, 3 ...Never use an arrow function as an object method if you need this to refer to the object. Arrow functions do not have their own this and will capture the outer (often global) context instead.
Ready to test yourself?
Practice JavaScript— quiz & coding exercises