apply:方法能劫持另外一个对象的方法,继承另外一个对象的属性.
Function.apply(obj,args)方法能接收两个参数
obj:这个对象将代替Function类里this对象
args:这个是数组,它将作为参数传给Function(args–>arguments)
Function.prototype.apply = function(thisArg=window ){
if (typeof this !== 'function') { // 调用call的若不是函数则报错
throw new TypeError('Error');
}
thisArg.fn = this;//将调用apply函数的对象添加到thisArg的属性中。
let result;
if(arguments[1]){ //如果有第二个参数,添加进去
result = thisArg.fn(arguments[1]);
}else{
result = thisArg.fn();
}
delete thisArg.fn;
return result;
}
call:和apply的意思一样,只不过是参数列表不一样.
Function.call(obj,[param1[,param2[,…[,paramN]]]])
obj:这个对象将代替Function类里this对象
params:这个是一个参数列表
Function.prototype.call = function(thisArg=window ,...arg){
if (typeof this !== 'function') { // 调用call的若不是函数则报错
throw new TypeError('Error');
}
thisArg.fn = this;//将调用apply函数的对象添加到thisArg的属性中。
const result = thisArg.fn(...arg);
delete thisArg.fn;
return result;
}
bind方法会创建一个新函数,当这个新函数被调用时,bind()的第一个参数将作为他运行时的this,后面参数为多个,不是数组。
Function.prototype.bind = function(thisArg,...args ){
if (typeof this !== 'function') { // 调用call的若不是函数则报错
throw new TypeError('Error');
}
let _this = this;//存储函数本身
let args = [...arg]; //提取后面的参数
return function F(){
if(this instanceof F){ //可能是一个构造函数
return _this.apply(this,args.concat([...arguments]));
}
return _this.apply(thisArg,args.concat([...arguments]));
}
}