call方法
/*
call(Fn,obj,...args)
Fn为要执行的函数 obj是this指向的对象 ...args是形参
*/
function call(Fn,obj,...args){
//判断obj对象是否存在
if(obj === undefined || obj === null){
obj = globalThis
}
//为obj添加临时方法
obj.temp = Fn
//调用temp方法
let result = obj.temp(...args)
//删除temp方法
delete obj.temp
//返回执行结果
return result
}
apply方法
/*
apply(Fn,obj,args)
Fn:要执行的函数 obj:this指向的对象 args:形参组成的数组
*/
function apply(Fn,obj,args){
//判断obj是否存在
if(obj == undefined || obj == null){
obj = globalThis
}
//为obj添加临时方法
obj.temp = Fn
//执行临时方法
let result = obj.temp(...args)
//删除临时方法
delete obj.temp
//返回结果
return result
}
bind方法返回的是一个函数 先传入的参数有效,后传入的参数无效
function call(Fn,obj,...args){
if(obj == undefined || obj == null)
obj = globalThis
obj.temp = Fn
let result = obj.temp(...args)
delete obj.temp
return result
}
/*
bind返回的是一个函数
例:
let fn = add.bind(obj,10,20)
console.log(fn(30,40)) 先传入的参数为10和20,后面传入的30,40不起作用
*/
function bind(Fn,obj,...args) {
return function (...args2){
return call(Fn,obj,...args,...args2)
}
}
function add(a,b){
return a+b+this.c
}
let obj = {
c:521
}
let fn3 = bind(add,obj,10,20)
console.log(fn3(30,40))