Call, Apply & Bind Methods in JavaScript - by Kunal Tandon - Medium
Call, Apply & Bind Methods in JavaScript - by Kunal Tandon - Medium
Search Medium
Get unlimited access to all of Medium for less than $1/week. Become a member
If you are a regular JavaScript developer, you must have heard of the methods
If the answer is no, don’t worry. By the end of this article, you will have a firm knowledge of
these methods.
function someMethod() {
console.log(this);
}
When someMethod() is executed in chrome’s console window, we get the Window object. As
this keyword refers to the top level Window object in a function’s scope.
var student = {
name: "Kunal",
age: 23
};
Notice how we used this keyword as if it is a student object. The method above uses
this.name to access the student object’s data.
When we try to call the Register function, we did not get the name printed as there is no
property named name in window object:
<FunctionName>.call(<objectToBindWithThis>, <FunctionParam1>,
<FunctionParam2>..)
To call the Register method with the call method, we use the statement:
Register.call(student, “JavaScript”, 99);
Output:
Notice, we get the value of this.name as Kunal . You can try modifying the function to use the
age property of student object as well.
For every call method, we have to send the student object to change the context of this
keyword.
Output:
We get the similar output as the call method. The only difference is the syntax of using
apply method.
Similar to call , the context of this keyword is updated only for the executed call.
The bind method call returns a new function which has the this keyword binded with the
object. We can call the function any number of times to execute the code.
Syntax:
Here, we binded the student object with the Register method & stored it in a variable named
bindedRegister .
Logging the bindedRegister in the console window gives a function. This is the binded
register function.
We will call the bindedRegister function with the statement below:
bindedRegister("JavaScript", 99);
Output:
Follow
1.7K 4
1.1K 7
Kunal Tandon in Developer’s Arena
2.1K 6
1.3K 2
40 2
React Dojo in JavaScript in Plain English
Lists
Leadership
30 stories · 16 saves
69
123
Yuvraj Upadhyay
30 1