The similarities and differences of call, apply and bind
In JavaScript, functions can change their this point in 3 ways, which are call, apply, bind. 3 of them are very similar, but there are differences. The table below can be very intuitive to see the difference between the three
| Method |
Whether the function is executed directly |
Parameters passed in |
Invocation mode |
| Pager |
Is |
(Context,arg1,arg2,arg3 ...)
The second argument is followed by an argument |
Function.call (Context,arg1,arg2,arg3 ...) |
| Apply |
Is |
(Context,[arg1,arg2,arg3 ...])
The second argument must be an array |
Function.apply (Context,[arg1,arg2,arg3 ...]) |
| Bind |
Whether |
(context)
Only one parameter |
var newfunction = function.bind (context);
Newfunction (Arg1,arg2,arg3 ...) |
Second, example:
1. Call
| 1 |
vara = {x: 1}; var b = function(y, z) { console.log(this.x + y + z) }; b.call(a, 3, 4);//此时b的this(即b执行时的上下文)被改变为a,因此this.x为1,第二个参数之后都是传给b实参。 |
2. Apply
| 1 |
vara = {x: 1}; var b = function(arr) { console.log(this.x + arr[0] + arr[1]) }; b.call(a, [3, 4]);//此时b的this(即b执行时的上下文)被改变为a,第二个参数是一个数组 |
3. Bind
| 1 |
vara = {x: 1}; var b = function (y, z) { console.log(this.x + y + z) }; varnewB = b.bind(a);//此时b的this(即b执行时的上下文)被改变为a,由此生成一个新函数,函数不会立即执行。 newB(3, 4);//函数此时才执行 |
Iii. Common Scenarios
1. Append between arrays
| 1 |
vararray1 = [12, "foo", {name: "Joe"}, -2458]; var array2 = ["Doe", 555, 100]; Array.prototype.push.apply(array1, array2); /* array1 值变为 [12 , "foo" , {name:"Joe"} , -2458 , "Doe" , 555 , 100] */View Code |
2. Get the maximum and minimum values in the array
| 1 |
varnumbers = [5, 458, 120, -215]; varmaxInNumbers = Math.max.apply(Math, numbers); //458 View Code |
3. Verify that it is an array (provided the ToString () method has not been rewritten)
| 1 |
functionisArray(obj){ returnObject.prototype.toString.call(obj) === ‘[object Array]‘; } View Code |
4. Class (pseudo) array using array method
| 1 |
vardomNodes = Array.prototype.slice.call(document.getElementsByTagName("*")); View Code |
5. Sum of Numbers
| 1 |
functionsum() { var numberSum = Array.prototype.reduce.apply(arguments, [function (prev, next) { returnprev + next; }]); console.log(numberSum); } sum(1, 2, 3); |
The similarities and differences of call, apply and bind