"this" keyword in Javascript
this Keyword
this is a special keyword in javascript where it doesn't behave as same as this in another programming languages like c# and Java. In these languages, this will return a reference to the current object.
Let's see an example
const person = {
name:"madhav",
age: 16,
walk() {
console.log(this);
}
}
person.walk();
//output: {name:"Madhav", age: 16, walk: f}
In the above example, this is returning a reference to the person object as expected. But this in javascript does not always work in that way. Let me show you an example.
const person = {
name:"madhav",
age: 16,
walk() {
console.log(this);
}
}
person.walk(); // It prints {name:"Madhav", age: 16, walk: f}
const walk = person.walk;
walk(); // It prints "undefined"
In this example, we are not calling the function we are just storing the function reference in walk constant, and we are calling walk() method.
What is happening here is in javascript, if we call a function as a method in the object this will always return a reference to that object.
However, if we call a function as a standalone function or outside the object this will return global object i.e. window object that is available in browsers.
We can resolve this issue using the bind method in javascript. So in javascript functions are objects. So in the above example, person.walk is an object. This will contain all methods which are available for an object.
Bind method:
bind() method is used to bind the function to an object. In this, whatever we passed as a first argument will determine as the value of this.
So if pass person object as an argument to the walk function then this will point towards person object no matter how we call the function.
const person = {
name:"madhav",
age: 16,
walk() {
console.log(this);
}
}
person.walk(); // It prints {name:"Madhav", age: 16, walk: f}
const walk = person.walk.bind(person);
walk(); // It prints {name:"Madhav", age: 16, walk: f}
So in the above example, we are binding walk method to the person object. That's why we got the person object as output instead of undefined.
So bind() function fixed our issue.