手动实现call
let obj={
name:'张三'
}
let obj1={
name:'李斯',
fn1:function(...args){
console.log(this.name,args);
}
}
obj1.fn1()//李斯 []
Function.prototype.myCall=function(context,...args){
const fn=this;
context=context||window;
context.fn1=fn;
const res=context.fn1(...args)
delete context.fn1;
return res
}
obj1.fn1.myCall(obj,1,2,3,4)//张三 [ 1, 2, 3, 4 ]
手动实现apply
Function.prototype.myApply=function(context,...args){
const fn=this;
context=context||window;
context.fn1=fn;
const res=args?context.fn1(...args[0]):context.fn1()
delete context.fn1;
return res
}
obj1.fn1.myApply(obj,[11,22,33])//张三 [ 11, 22, 33 ]
手动实现bind
Function.prototype.myBind=function(context,...args){
const argu=args;
const that=this;
function fnBind(){
return that.myApply(context,argu.concat(...arguments))
}
return fnBind
}
obj1.fn1.myBind(obj,111,222)(333,444)//张三 [ 111, 222, 333, 444 ]
手动实现Array.myIsArray,用来判断传入的是否是一个数组,返回true/false
Array.myIsArray=function(arr){
return Object.prototype.toString.call(arr)==='[object Array]'
}
console.log(Array.myIsArray([1,2,3]));