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 () {
// 这个时候的arguments是指bind返回的函数传入的参数
var bindArgs = Array.prototype.slice.call(arguments)
return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs))
}
fNOP.prototype = this.prototype
fBound.prototype = new fNOP()
return fBound
}
bind的模拟实现
于 2022-02-02 14:31:07 首次发布