本文共 1273 字,大约阅读时间需要 4 分钟。
let self=this var mybound=function (){ /* bind 的回调函数 (bind的执行返回的是一个函数) */ console.log(arguments,arr) arr=arr.concat(arguments)/* 与上一个splice 同样的效果 */ self.apply(context,arr) /* 使用apply 改变 调用bind函数的this指向 */ }
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)()
转载地址:http://cfizk.baihongyu.com/