bind() 方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。(来自于 MDN )
Function.prototype.bind = function (context) {
if (typeof this !== 'function') {
throw new Error('Function.prototype.bind - what is trying to be bound is not callable')
}
var self = this
// 获取bind函数从第二个参数到最后一个参数
var args = Array.prototype.slice.call(arguments, 1)
var fNOP = function() {}
var fBound = function () {
// 获取bind返回函数的传入参数
var bindArgs = Array.prototype.slice.call(arguments)
// 当作为构造函数时,this指向实例,此时结果为true,将绑定函数的this指向该实例,可以让实例获得来自绑定函数的值
// 当作为普通函数时,this指向window,此时结果为false,将绑定函数的this指向context
return self.apply(this instanceOf fNOP ? this : context, args.concat(bindArgs))
}
fNOP.prototype = this.prototype
fBound.prototype = new fNOP()
return fBound
}