JavaScript Function this
Understanding the 'this' keyword in functions
🎯 What is 'this' in JavaScript?
The 'this' keyword refers to the object that is currently executing the function. Its value depends on how the function is called.
let person = {
name: "Alice",
greet: function() {
return "Hello, I'm " + this.name;
}
};
console.log(person.greet()); // 'this' refers to person object
Output:
"Hello, I'm Alice"
Different 'this' Contexts
Global Context
'this' refers to global object
console.log(this); // window
Object Method
'this' refers to the object
obj.method(); // this = obj
Constructor
'this' refers to new instance
new MyClass(); // this = instance
Arrow Functions
'this' is inherited from parent
() => this; // inherited
🔹 'this' in Object Methods
When a function is called as an object method, 'this' refers to that object:
let car = {
brand: "Toyota",
model: "Camry",
getInfo: function() {
return this.brand + " " + this.model;
},
start: function() {
return this.brand + " is starting...";
}
};
console.log(car.getInfo());
console.log(car.start());
Output:
Toyota Camry
Toyota is starting...
🔹 'this' in Regular Functions
In regular functions, 'this' depends on how the function is called:
function showThis() {
console.log("this is:", this);
}
// Global function call
showThis(); // this = window (in browser)
let obj = {
name: "MyObject",
method: showThis
};
// Method call
obj.method(); // this = obj
Output:
this is: Window {...}
this is: {name: "MyObject", method: ƒ}
🔹 'this' in Arrow Functions
Arrow functions don't have their own 'this' - they inherit it:
let person = {
name: "Bob",
// Regular function
regularGreet: function() {
return "Hello from " + this.name;
},
// Arrow function
arrowGreet: () => {
return "Hello from " + this.name; // 'this' is not person!
},
// Arrow function inside regular function
delayedGreet: function() {
setTimeout(() => {
console.log("Delayed: " + this.name); // 'this' is person
}, 1000);
}
};
console.log(person.regularGreet());
console.log(person.arrowGreet());
Output:
Hello from Bob
Hello from undefined
🔹 Constructor Functions and 'this'
In constructor functions, 'this' refers to the new object being created:
function Person(name, age) {
this.name = name;
this.age = age;
this.introduce = function() {
return "Hi, I'm " + this.name + " and I'm " + this.age;
};
}
let person1 = new Person("Alice", 25);
let person2 = new Person("Bob", 30);
console.log(person1.introduce());
console.log(person2.introduce());
Output:
Hi, I'm Alice and I'm 25
Hi, I'm Bob and I'm 30