实现call、apply、bind方法
实现call方法
实现代码展示
js
Function.prototype.myCall = function (context, ...args) {
if (typeof this !== 'function') {
throw new TypeError('Call must be called on a function')
}
context = context || window
const fn = Symbol('fn')
context[fn] = this
const result = context[fn](...args)
delete context[fn]
return result
}实现apply方法
实现代码展示
js
Function.prototype.myApply = function (context, args) {
if (typeof this !== 'function') {
throw new TypeError('Apply must be called on a function')
}
context = context || window
const fn = Symbol('fn')
context[fn] = this
const result = context[fn](...args)
delete context[fn]
return result
}实现bind方法
实现代码展示
js
Function.prototype.myBind = function (context, ...args) {
if (typeof this !== 'function') {
throw new TypeError('Bind must be called on a function')
}
context = context || window
const fn = Symbol('fn')
context[fn] = this
return function (...newArgs) {
const result = context[fn](...args, ...newArgs)
delete context[fn]
return result
}
}