Apply&Bind

apply()

  • apply() is different from call() when there exists parameters
1
2
3
4
5
6
7
8
9
10
function addNumbers(a, b, c){
return this.firstName + " calculated " + (a + b + c);
}
var r = {
firstName: 'Rosie'
}
// call() version
addNumbers.call(r, 1, 2, 3)
// apply() version
addNumbers.apply(r, [1, 2, 3])
  • Use cases

    • When a function does not accept an array, apply() spread out values in an array

      1
      2
      3
      4
      var nums = [5, 7, 1, 4, 2]

      // Math.max(nums) will not work
      Math.max.apply(this, nums);

bind()

The parameters work like call(), but bind() returns a function with ‘this’ bound already. Also, we can just pass a part of parameters, and store this function for later uses.

1
2
var meCal = addNumbers(r, 1, 2);
meCal(3);

setTimeout(function, elapseTime) works on window object.

A tricky Issue

1
2
3
4
5
6
7
8
var r = {
firstName: 'Rosie',
sayHi: function(){
setTimeout(function(){
console.log("Hi " + this.firstName);
}, 1000)
}
}

Since setTimeout is called 1000ms later, so this is refer to the window.

By attaching call() or apply(), it can refer to the declared object. To save the function for later uses, bind() can be used.

1
2
3
setTimeout(function(){
console.log("Hi " + this.firstName);
}.bind(this), 1000);

The ‘new’ keyword

new‘ will set the context of this