实现call,apply,bind
/**
* 实现call
*/
Function.prototype.theCall = function () {
const [context, ...args] = arguments
context.fn = this
context.fn(...args)
delete context.fn
}
/**
* 实现apply
*/
Function.prototype.theApply = function () {
const [context, args] = arguments
context.fn = this
context.fn(...args)
delete context.fn
}
/**
* 实现bind
*/
Function.prototype.theBind = function () {
const fn = this
const [context, ...outArgs] = arguments
const bound = function (inArgs) {
const args = outArgs.concat(inArgs)
if (this instanceof bound) {
return new fn(args)
} else {
return fn.theApply(context, args)
}
}
return bound
}