call
Function.prototype.myCall = function (context = window, ...args) {
if (this === Function.prototype) {
return undefined
}
const context = context || window
const fn = Symbol()
context[fn] = this
const result = context[fn](...args)
delete context[fn]
return result
}
apply
Function.prototype.myApply = function (context = window, args) {
if (this === Function.prototype) {
return undefined
}
const context = context || window
const fn = Symbol()
let result
if (Array.isArray(args)) {
result = context[fn](...args)
} else {
result = context[fn]()
}
delete context[fn]
return result
}
bind
Function.prototype.myBind = function (context, ...args) {
if (this === Function.prototype) {
throw new TypeError('Error')
}
const _this = this
return function f(...args1) {
if (this instanceof f) {
return new _this(...args, ...args1)
} else {
return _this.apply(context, args.concat(...args1))
}
}
}