bind
的特点:
- 返回的是一个函数
- 可以在绑定时传参,使用时继续传参
- 返回函数继承绑定函数
- 对返回函数使用
new
时,bind
绑定的this
无效,传参有效
Function.prototype.bind = Function.prototype.bind || function (context) {
if(typeof this !== 'function') {
throw new Error('Function.prototype.bind - what is trying to be bound is not callable');
}
const self = this
const args = Array.prototype.slice.call(arguments, 1)
const fBound = function () {
const bindArgs = [...arguments]
return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs))
// this instanceof fNOP判断是否是new操作
// return 是为了能够返回 函数的执行返回结果
}
const fNOP = function () {}
fNOP.prototype = this.prototype
fBound.prototype = new fNOP()
return fBound
}