call
Function.prototype.myCall = function (context, ...args) {
const fn = Symbol('fn') // Symbol防止重复
context[fn] = this // this是调用call的函数
const res = context[fn](...args)
delete context[fn]
return res
}
apply
- apply和call的差别,仅在于参数。
Function.prototype.myApply = function (context, args) {
const fn = Symbol('fn')
context[fn] = this
const res = context[fn](...args)
delete context[fn]
return res
}
bind
Function.prototype.myBind = function (context, ...args) {
const self = this
return function () {
return self.apply(context, args) // 使用apply
}
}