Apply&Bind
apply()
apply()
is different fromcall()
when there exists parameters
1 | function addNumbers(a, b, c){ |
Use cases
When a function does not accept an array,
apply()
spread out values in an array1
2
3
4var 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 | var meCal = addNumbers(r, 1, 2); |
setTimeout(function, elapseTime)
works on window object.
A tricky Issue
1 | var r = { |
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 | setTimeout(function(){ |
The ‘new’ keyword
‘new
‘ will set the context of this