In my last post, I discussed the Function constructor. How the function object created from it and the properties and methods of the function object.
In this article, we will go into the details of the following three function methods.
- call()
- apply()
- bind()
They are basically used to call the function (except bind, bind() returns a new function that we can use as per our need). They all take a this value depending upon the context to execute the function in that context. Let's take a look at each one in detail.
call()
MDN definition : The call() method calls a function with a given this value and arguments provided individually.
Syntax: func.call([thisArg[, arg1, arg2, ...argN]])
- thisArg: optional (this will be the value upon which the function would call)
- arg1, arg2, ...argN: optional (arguments of the function)
- the first argument represents a value on which the function would call (it refers to the current object/the calling object)
- other arguments represent the value to the parameter of the function
Let's take a look at an example:
// defining a global variable
var lastName = 'global_name';
const func = function(firstName) {
return firstName + " " + this.lastName; /** the value of 'this'
is defined how we call the function */
}
// this object is passed as the first argument to the call method
var person = {
lastName: 'person_name'
}
// calling the function usually
func('Sachin'); // Sachin global_name
/** calling the function using the call method and setting the
'this' value to the 'person' object */
func.call(person, 'Sachin'); // Sachin person_name
// using call method without passing the first argument
func.call(); // undefined global_name
// passing the first argument as null or undefined
func.call(null, 'Sachin'); // Sachin global_name
func.call(undefined, 'Sachin'); // Sachin global_name
/******************** in strict mode*****************/
func.call(); /** Cannot read property 'lastName' of undefined*/
func.call(null, 'Sachin'); /** Cannot read property 'lastName' of null*/
func.call(undefined, 'Sachin'); /** Cannot read property
'lastName' of undefined*/
As seen from the example, we can use the call method to call a function on any object.
When usually calling the function then
thisvalue will set to the global objectwindow. Thiswindowobject is having a propertylastNamewhich we defined globally in our code will return from the function.When calling the function using the call method and passing the first argument a
personobject thenthisvalue will set to thatpersonobject (notwindowobject this time) and itslastNameproperty will return.Using the call method without passing any arguments,
thisvalue will set to the global objectwindowand its propertylastNamewill return.When the first argument passed is
nullorundefinedthen still thethiswill set to the globalwindowobject in this case.Caution: For strict mode
In 'strict mode', the value of
thiswill beundefined. To know about strict mode refer to this documentation.
apply()
Syntax: func.apply(thisArg, [ argsArray])
- thisArg: (this will be the value upon which the function would call)
- argsArray: optional (arguments of the function passed in an array)
apply() is almost similar to call() except that it takes an array as a second argument and passes the members of that array as arguments to the calling function.
Example:
var name = 'Sachin';
const func = function (age, hobby) {
return (this.name + ' is ' + age + ' years old and his hobby is '
+ hobby);
};
var person = {
name: 'John'
}
func(); /** Sachin is undefined years old and his
hobby is undefined*/
func.apply(); /** Sachin is undefined years old and his
hobby is undefined*/
console.log(func() === func.apply()); /** true*/
func('15', 'writing'); /** Sachin is 15 years old and his
hobby is writing*/
func.apply(undefined, ['15', 'writing']); /** Sachin is 15 years
old and his hobby is writing*/
func.apply(null, ['15', 'writing']); /** Sachin is 15 years
old and his hobby is writing*/
/********* changing 'this' to 'person' object*********/
func.apply(person, ['20', 'music']); /** John is 20 years
old and his hobby is music*/
/**************** strict mode ***************/
/** Cannot read property 'name' of undefined*/
func();
func('15', 'writing');
func.apply();
func.apply(undefined, ['15', 'writing']);
/** Cannot read property 'name' of null */
func.apply(null, ['15', 'writing']);
bind()
Syntax: func.bind(thisArg[, arg1[, arg2[, ...argN]]])
- bind() method creates and returns a copy of the function
func. - when that new function is called, it has it's
thisvalue set to the value provided bythisArg. - arg1, arg2,..., argN are arguments that prepends to the arguments of that new returned function.
Let's understand this with an example:
// defining a person object
/** this object has a property 'age' and a method
'getNameAndAge' */
const person = {
age: 42,
getNameAndAge: function(name) {
return name + ' ' + this.age;
}
}
// calling the method on the 'person' object directly
person.getNameAndAge('Sachin'); // Sachin 42
// assigning the reference of the method to variable nameAndAge
const nameAndAge = person.getNameAndAge;
// calling the function assigned to nameAndAge by referencing it
nameAndAge('Sachin'); /** Sachin undefined (the function gets
invoked at the global scope)*/
// use of bind method
const boundNameAndAge = nameAndAge.bind(person, 'Sachin');
boundNameAndAge() /** Sachin 42 (bind method creates
a new function and bounds 'this' value to 'person' object)*/
// bind without any arguments
const boundNameAndAge = nameAndAge.bind();
boundNameAndAge('Sachin') // Sachin undefined
// setting 'this' to 'undefined'
const boundNameAndAge = nameAndAge.bind(undefined, 'Sachin');
boundNameAndAge() // Sachin undefined
// setting 'this' to 'null'
const boundNameAndAge = nameAndAge.bind(null, 'Sachin');
boundNameAndAge() // Sachin undefined
When we are executing
nameAndAge('Sachin');, we are executing that function in the global scope andthishere refers to the globalwindowobject and we have not definedagein the global scope, that's why it returnsundefined.-
const boundNameAndAge = nameAndAge.bind(person, 'Sachin');-
bindmethod creates and returns a copy of nameAndAge function and setsthistopersonobject. We are assigning that newly created function to variableboundNameAndAge. When we executeboundNameAndAge(), has it'sthisset topersonandageproperty ofpersonobject returns.
-
In case of no arguments or
thisset tonullorundefined, thethisvalue for the newly created function is decided by thethisof the executing scope.
Conclusion
- call() and apply() executes the function immediately, whereas bind() returns a new function.
- the object/value on which the function executes depends on the
thisvalue defined by the context.
Thanks for reading. If you found this article helpful please like and share it with others so that they will also get the benefit. Feedbacks are welcome: Twitter | Instagram | LinkedIn
Top comments (0)