apply/call/bind comparison
- Parameters: apply passes in an array, call/bind passes in multiple parameters, and bind can continue to pass parameters during runtime.
- Execution: apply/call is executed immediately, bind will not be executed immediately
Use of apply
use
- Hijack methods and inherit properties from other objects.
- Array parameters can be converted into multiple parameters (es6's operation expander also has this function)
grammar
fun.apply(thisArg, [argsArray])
- thisArg: fun specifies this when running
- argsArray: receives the array type and converts the array into multiple parameters during execution
example:
fun.apply(obj, [a,b,c])
=>fun(a,b,c)
- The this object involved in fun will point to obj
Common uses
- The maximum and minimum values of the array.
- Max.max and Max.min parameter types are multi-parameter forms
How to implement apply?
// apply本身功能
console.log(Math.max(4,1,3));
console.log(Math.max.apply(null, [4,1,3]));
// 4
// 4
// 实现apply
Function.prototype.apply = function fn(context,param){
console.log(`my apply...`);
// 1. 修改方法内部this指向 => ctx
let ctx = context ? context : window;
ctx.fn = this; // this是当前方法,fn调用者是ctx(因此fn内this指向ctx)
// 2.参数转换: 只有数组需要
if(Array.isArray(param)){
// 字符串和数组相加,数组会自动转为字符串 例如'test ' + [1,2,3] => 'test 1,2,3'
return eval('ctx.fn(' + param + ')');
}else{
return ctx.fn();
}
}
// TEST
console.log(Math.max(4,1,3));
console.log(Math.max.apply(null, [4,1,3]));
// 4
// my apply...
// 4
call syntax
fun.call(obj, param1, param2....)
- obj: replace this object in fun
- params: receives multi-parameter types without any conversion
scenes to be used
[].slice.call(arguments)
You need to understand slice syntax first
slice(startIndex, endIndex)
Slice the array, the original array remains unchanged, and the new array is returned- startIndex defaults to 0, endIndex defaults to the last element subscript
- slice() returns the entire array
- slice(1) returns an array starting from index=1 to the last element
a=['a','b','c'];
b=a.slice();
c=a.slice(1);
console.log('a=',a);
console.log('b=',b);
console.log('c='