45 Mins upper-intermediate
16. The 'this' Keyword
Object Context
The 'this' Keyword
In JavaScript, this refers to the object that is executing the current function. It is dynamic, meaning its value changes depending on how the function is called.
๐ Method Context
When used inside a method (a function attached to an object), this refers to the object itself.
const user = {
name: "Alice",
greet: function() {
console.log("Hello, I am " + this.name);
}
};
user.greet();
OutputHello, I am Alice
๐ Global Context & Lost Context
If you call a regular function out in the open, this defaults to the Global Window object (or undefined in strict mode). This often breaks when passing methods as callbacks.
const obj = {
value: 42,
printVal: function() {
console.log(this.value);
}
};
// Works perfectly
obj.printVal();
// Context is lost because the function is separated from the object!
const detachedFunc = obj.printVal;
try {
detachedFunc();
} catch (e) {
console.log("Context lost!");
}
Output42
Context lost!
Context lost!
๐น Arrow Functions and 'this'
Arrow functions do not have their own this. They inherit this from the surrounding scope where they were defined (Lexical Scoping). This fixes the "lost context" problem in callbacks.
const timer = {
seconds: 0,
start: function() {
// Arrow function inherits 'this' from the start() method
// If this was a regular function, 'this' would be the Global window.
const tick = () => {
this.seconds++;
console.log(this.seconds);
};
tick();
}
};
timer.start();
Output1
Knowledge Check
Ready to test your understanding of 16. The 'this' Keyword?