Hi Guy’s Welcome to Proto Coders Point, In this article let’s understand 'this'
keyword in JavaScript and how it plays an important role in JavaScript.
The 'this'
keyword is the context in which function it is defined. It is dynamically refers to object that is currently executing the function.
For better understanding let’s refer below code and learn how this
keyword context works and how to make use of call()
method in JavaScript that allows borrowing methods from one object to another.
Source Code
let obj1 = { firstName: "Rajat", lastName: "Palankar", fullName : function(){ console.log(this.firstName + " " + this.lastName); } } let obj2 = { firstName: "Suraj", lastName: "Somanche", } obj1.fullName(); //"Rajat Palankar" obj1.fullName.call(obj2); // "Suraj Somnache"
In Above JS Snippet Code, we have two objects, named obj1
and obj2
, each of this object containing key/Value pair properties firstName
and lastName
. With this obj1
has an additional method called fullName
which simply logs the full name by concatenating firstName
and lastName
.
Now, let’s check out how the this
keyword operates in the context within this fullName
method.
When fullName()
is called on obj1
by doing something like: obj1.fullName()
, here this
context refers to the obj1
object itself. Thus, this.firstName
will return us “Rajat” and this.lastName
will return us “Palankar”, and concat it and print “Rajat Palankar” on screen.
But what if we want to reuse the fullName
method that is defined in obj1
but this
context should point to obj2
object? This is when we can make use of call()
method in javascript.
The call()
method allows us to invoke a function with a specific this
context. Here’s how it works:
obj.fullName.call(obj2);
The line, obj.fullName
refers to the fullName
method of obj
, and call(obj2)
is used to invoke obj1
with obj2
as it’s this
context. So, Now this context is refering to obj, In this way now, this.firstName
inside the fullName
function of obj1
is now refers to obj2.firstName
and this.lastName
refers to obj2.lastName
. Consequently, “Suraj Somanche” is logged to the console.