关于bind的疑问

218次阅读

var unboundBind = Function.prototype.bind
  , bind = Function.prototype.call.bind(unboundBind);

请教为什么可以这样使用,这样使用的好处在哪里?

不吃芒果

最终得到的bind函数可将任意方法和this绑定在一起,返回绑定后的新函数,相当于一个组合作用
示例:

// 方法
function test() {
  console.log(this.value)
}

// this
var obj = {
  value: 1
}

var unboundBind = Function.prototype.bind,
  bind = Function.prototype.call.bind(unboundBind);

// 将方法和this进行绑定
// 返回绑定后的函数
var func = bind(test, obj)

func() // 输出1

关于bind的疑问

分析:

1.var unboundBind = Function.prototype.bind, bind =Function.prototype.call.bind(unboundBind);

2.bind = unboundBind.Function.prototype.call;

3.bind = (Function.prototype.bind).(Function.prototype.call)

调用bind函数:var func = bind(method,this)

等效:func = (Function.prototype.bind).(Function.prototype.call)(method,this)

化简:func = method.bind(this)

dablwow80

简单说就是省掉一个call()

月夜枫

正文完