JavaScript原生实现的call、apply和bind方法
1.实现call方法
Function.prototype.myCall = function(context, ...args){ if(this === Function.prototype){ //防止直接调用Fucntion.prototype.myCall() return undefined } context = context || window //选择指向的对象 context.fn = this //给对象添加调用者的方法 let result = context.fn(...args) //执行函数,并返回结果 delete context.fn //删除添加的方法 return result //返回结果,无结果返回时为undefined }
2.实现apply方法
Function.prototype.myApply = function(context, args){ if(this === Function.prototype){ //防止直接调用Function.prototype.myApply() return undefined } context = context || window //选择指向的对象 context.fn = this //给对象添加新方法 let result = null if(Array.isArray(args){ //判断是否传入的是数组 result = context.fn(...args) //执行带参数的函数 }else{ result = context.fn() //忽略参数执行函数 } delete context.fn //删除方法 return result //返回结果 }
3.实现bind方法
Function.prototype.myBind = function(context, ...args1){ if(this === Function.prototype){ return undefined } const _this = this return function F(...args2){ if(this instanceof F){ //判断是否通过new来创建函数 return new _this(...args1, ...args2) //如果是,则直接通过new方法调用这个函数 } return _this.call(context, ...args1, ...args2) //如果不是,通过call重新改变this方向 } }

浙公网安备 33010602011771号