js手撕this绑定--模拟bind函数的实现
bind与apply和call都不同,函数调用它会返回一个新的函数,再次调用才是执行体本身,这种模式也就导致了它传递参数可以分批次依序传递了
Function.prototype.imibind=function(obj,...args){ let fn=this function recurse(...newargs){ obj=(obj!==undefined&&obj!==null)?Object(obj):window obj.fn=fn var finalArgs=[...args,...newargs] var result=obj.fn(...finalArgs) delete obj.fn return result } return recurse } function sum(n1,n2,n3){ console.log("sum"); console.log(this); return n1+n2+n3 } var obj={name:'xwl'} var of=sum.imibind(obj,10) var result=of(20,30) console.log(result);