JS 实现一个基本的bind
bind()方法介绍:
原生bind,第一个参数是绑定的上下文对象,第二个参数开始是传递的参数,同时bind方法返回一个函数,需要手动执行。
bind(ctx, arg1, arg2 ...)
代码实现:
// 实现的_bind
Fucntion.prototype._bind = function(ctx) {
const that = this // 保存当前环境this对象
// arguments代表调用_bind()传递的参数,slice处理取出第二项到length-1项的参数
const args = [].slice.call(arguments, 1, arguments.length-1)
return function() {
that.apply(ctx, args) // ctx表示执行_bind的对象
}
}
function a(eat, age, hobby) {
console.log(this.name + eat + age + hobby) // zhangsanapple18football
}
let b = { name: "zhangsan" }
a._bind(b, "apple", 18, "football")

浙公网安备 33010602011771号