call方法重写
Function.prototype.myCall = function() {
let arr = [...arguments];
let obj = arr.shift()||window;
obj.p = this;
const result = obj.p(...arr);
delete obj.p;
return result;
}
apply方法重写
Function.prototype.myApply = function(){
let arr = [...arguments];
let obj = arr[0]||window;
obj.p = this;
let result;
if(!arr[1]){
result = obj.p();
}else{
result = obj.p(...arr[1]);
}
delete obj.p;
return result;
}
bind方法重写
bind简单版的不带new
首先看一下原生的bind输出效果
function fun01 (a, b, c) {
console.log(this.n, a, b, c);
}
var obj01 {n: 'teriri'};
fun01.bind(obj01, 'ss','sss')('rere'); // teriri ss sss rere
bind带了函数柯里化
因此重写bind方法如下:
Function.prototype.myBind = function() {
const self = this;
const arr = [...arguments];
const thisValue = arr.shift();
return function () {
arrAdd = [...arr, ...arguments];
return self.apply(thisValue, arrAdd);
}
}
bind复杂版要带new
。。。暂时不写