JavaScript beginners often get confused about this. But the idea can be simplified.
Think of this as โwho is calling the function.โ
- this Inside Normal Functions
In a regular function, this depends on how the function is called.
function showName() {
console.log(this);
}
showName();
In browsers, this usually prints the global object (window).
Because the function was called without an object.
So the caller is the global environment.
- this Inside Objects
When a function is inside an object, this refers to the object calling the method.
const person = {
name: "Alice",
greet: function () {
console.log("Hello, my name is " + this.name);
}
};
person.greet();
Because person is calling greet(), so this becomes person.
What call() Does
call() lets you manually choose what this should be.
function greet() {
console.log("Hello " + this.name);
}
const person = { name: "Alice" };
greet.call(person);
Even though greet is not inside the object, we force this to be person.
Passing Arguments with call()
function introduce(age, city) {
console.log(this.name + " is " + age + " years old from " + city);
}
const user = { name: "Bob" };
introduce.call(user, 25, "London");
4. What apply() Does
apply() is almost the same as call().
The only difference:
Arguments are passed as an array
function introduce(age, city) {
console.log(this.name + " is " + age + " years old from " + city);
}
const user = { name: "Charlie" };
introduce.apply(user, [30, "New York"]);
*What bind() Does
*
bind() does not call the function immediately.
Instead, it creates a new function with this fixed.
function greet() {
console.log("Hello " + this.name);
}
const user = { name: "David" };
const greetUser = greet.bind(user);
greetUser();
Output
Hello David
Here, bind() creates a new function that always uses user as this.
Top comments (0)