this
Keyword 👤The this
keyword in JavaScript refers to the object that is executing the current function.
In the global scope, this
refers to the global object (window
in browsers):
console.log(this); // window (in browser)
function showThis() {
console.log(this);
}
showThis(); // window (in non-strict mode)
const person = {
name: "Alex",
greet: function () {
console.log("Hello, I am " + this.name);
}
};
person.greet(); // Hello, I am Alex
this
Arrow functions inherit this
from their lexical scope (parent):
const user = {
name: "Sam",
greet: () => {
console.log("Hi, I am " + this.name);
}
};
user.greet(); // Hi, I am undefined
Click to see how this
works inside an object method:
this
in global → global object (like window
)this
in function (non-strict) → global objectthis
in object method → that objectthis
in arrow function → parent scopethis
, and arrow functions when you want it to inherit from its parent.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!