举例
let arr = [1, 3, 2, 8];
console.log(Math.max(arr)); //NaN
console.log(Math.max.call(Math, ...arr)); //8
console.log(Math.max.apply(Math, arr)); //8
console.log(Math.max(...arr)); //8
call
源码思路
function call(thisArg){
let context = thisArg || window;
context.func = this;
let params = Array.from(arguments).slice(1);
let res = arguments.length > 1 ? context.func(...params) : context.func();
delete context.func;
return res;
}
apply
源码思路
function apply(thisArg, params){
let context = thisArg || window;
context.func = this;
let res = params && params.length > 0 ? context.func(...params) : context.func();
delete context.func;
return res;
}
bind
源码思路
function bind(context){
let ctx = deepClone(context) || window;
ctx.func = this;
let args = Array.form(arguments).slice(1);
return function(){
let allArgs = args.concat(Array.form(arguments));
let res = arguments.length > 1 ? ctx.func(...allArgs) : ctx.func();
return res;
}
}