⏱ 0:01est. 6 min
Chapter 50- call(), apply(), and bind() (Borrowing,Curring)
Notes
Example 1
var person = {
firstname: ‘John',
lastname: ‘Doe',
getFullName: function(){
var fullname = this.firstname + this.lastname;
return fullname;
}
}
var logName = function(lang1,lang2){
console.log(‘logged' + this.getFullName();
}
logName() // this will fail.
var logPersonName = logName.bind(person);
logPersonName();
Example 2
var person = {
firstname: ‘John',
lastname: ‘Doe',
getFullName: function(){
var fullname = this.firstname + this.lastname;
return fullname;
}
}
var logName = function(lang1,lang2){
console.log(‘logged' + this.getFullName();
}.bind(person);
logName() // this will work.
#.bind creates copy of the function we are calling it on
Example 3 - Call is used to call the function
var person = {
firstname: ‘John',
lastname: ‘Doe',
getFullName: function(){
var fullname = this.firstname + this.lastname;
return fullname;
}
}
var logName = function(lang1,lang2){
console.log(‘logged' + this.getFullName();
}
logName() // this will fail.
// calling with reference object and params
logName.call(person,'en'.'es');
Example 4 - apply - does the same exact thing as call but it takes an array as a parameter
logName.appy(person,['en'.'es']);
Example 5 -Creating it on the fly and calling it using apply
(function(lang1,lang2){
console.log(‘logged' + this.getFullName();
}).apply(person,[‘en','es']);
We can use call, apply in function borrowing in objects
function currying - binding (creating new copy of the function)
function multipy(a,b){
return a*b;
}
//bind with params, bind is not executing the function
//giving params sets permanent values with bind when copy of function is made
//var a = 2 in following function
var multipyByTwo = multipy.bind(this,2)
multipyByTwo(3); // OUTPUT - 6
#BIGWORD Function Currying - Creating a copy of the function with some preset parameters - Very useful in mathematical situations