4-50 call(), apply(), and bind()

bigword alert : Function currying

  • creating a copy of a function but with some preset parameters.

  • The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.REF


bind 複製function,並將其中的 this 設成給定的物件,回傳複製的function

  • The call() method calls a function with a given this value and arguments provided individually.REF

call 將function中的this改為thisArg, 並用後面的參數invoked 該function

  • The apply() method calls a function with a given this value and arguments provided as an array REF

apply和call功能相同,差別只有function的參數要用array傳入

1
2

fun.call(thisArg[, arg1[, arg2[, ...]]])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

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());
console.log('Arguments: ' + lang1 + ' ' + lang2);
}

var logPersonName = logName.bind(person);
logName();
logName.call(person,'en','es');
logName.apply(person,['en','es']);

When is this used in real life?

  • function borrowing
function borrowing
1
2
3
4
5
6

var person2 = {
firstname : 'Jane';
lastname : 'Doe';
}
person.getFullName.apply(person2);
  • function currying
function currying
1
2
3
4
5
6
7

function multiply(a,b){
return a * b;
}
var multiplyByTwo = multiply.bind(this,2);
// set first parameter(a) = 2, reutrn a new copy of multiply function
console.log(multiplyByTwo(4));