call
1 Function.prototype.myCall=function(thisArg,...args){ 2 let fn=this //隐式调用 3 thisArg=(thisArg!==null&&thisArg!==undefined)?Object(thisArg):window //传undefined null 指向window全局 4 thisArg.fn=fn //1 5 let result=thisArg.fn(...args) //2 6 delete thisArg.fn //3 1 2 3不用call调用 7 return result //call函数有返回值 8 } 9 10 function foo(){ 11 console.log("foo调用了",this) 12 } 13 function sum(num1,num2){ 14 return num1+num2 15 } 16 foo.myCall() 17 let re=sum.myCall({},20,30) 18 console.log(re)
apply
1 Function.prototype.myApply=function(thisArg,argArray){ 2 let fn=this 3 thisArg=(thisArg!==null&&thisArg!==undefined)?Object(thisArg):window 4 thisArg.fn=fn 5 let result 6 //一: 7 // if(!argArray){//没传值时 8 // result=thisArg.fn() 9 // }else{//传值时 10 // result=thisArg.fn(...argArray) 11 // } 12 //二: 13 // argArray=argArray?argArray:[] 14 //三: 15 argArray=argArray||[] 16 result=thisArg.fn(...argArray) 17 delete thisArg.fn 18 return result 19 } 20 21 function foo(){ 22 console.log("foo调用了",this) 23 } 24 function sum(num1,num2){ 25 return num1+num2 26 } 27 foo.myApply({}) 28 let re=sum.myApply({},[20,30]) 29 console.log(re)
bind
1 Function.prototype.myBind=function(thisArg,...argArray){ 2 //1.获取到真实需要调用的函数 3 let fn=this 4 //2.绑定this 5 thisArg=(thisArg!==null&&thisArg!==undefined)?Object(thisArg):window 6 function proxyFn(...arg){ 7 //3.将函数放到thisArg中进行调用 8 thisArg.fn=fn 9 //特殊:对两个传入的参数进行合并 10 let finalArg=[...argArray,...arg] 11 let result=thisArg.fn(...finalArg) 12 delete thisArg.fn 13 //4.返回结果 14 return result 15 } 16 return proxyFn 17 } 18 19 function foo(){ 20 console.log("foo执行了",this) 21 } 22 function sum(num1,num2, num3){ 23 console.log(num1,num2,num3) 24 return num1+num2+num3 25 } 26 27 let fn=foo.myBind({}) 28 fn() 29 30 let su=sum.myBind({},2,3) 31 let result=su(5) 32 console.log(result)
标签:function,let,bind,argArray,call,result,thisArg,apply,fn From: https://www.cnblogs.com/KooTeam/p/17659376.html