手动实现bind函数 ⭐ 实现步骤 判断调用的对象是否是function保存传入到调用的的函数(第一部分形参)定义一个回调函数作为bind函数返回定义的函数使用箭头,为了就是保存执行上下文中上文中的this,避免在定义该回调函数以后this指向改变了。当然除了使用箭头函数你也可以在回调函数之前保存this因为返回回调函数之后,可能还有继续传入参数的,所以还要在保存一次与上述2中的arr做拼接。array.concat()就是实现数组拼接的方法之一最后一步就是改变调用函数的this指向啦,并将mybound返回 ⭐保存this的方法一 let self=this var mybound=function (){/* bind 的回调函数 (bind的执行返回的是一个函数) */ console.log(arguments,arr) arr=arr.concat(arguments)/* 与上一个splice 同样的效果 */ self.apply(context,arr) /* 使用apply 改变 调用bind函数的this指向 */ } ⭐原生bind Function.prototype.mybind=function(context){ if(typeof this!=="function"){ /* 判断调用bind 是否是函数 */ throw new Error("this not a function") /* 抛出错误 直接在浏览器报错啦 */ } var arr=[].splice.call(arguments,1)/* 使用call捕获从第二个开始传入的参数 */ //使用箭头函数避免this指向改变 var mybound=()=>{/* bind 的回调函数 (bind的执行返回的是一个函数) */ // console.log(arguments,arr) arr=arr.concat(arguments)/* 与上一个splice 同样的效果 */ this.apply(context,arr) /* 使用apply 改变 调用bind函数的this指向 */ } return mybound } var obj={ name:"lijia" } function foo(age,pp){ console.log(this.name,age,pp) } foo.mybind(obj,20,30)()