call和apply调用后立马执行,它们传参不同,bind会返回一个函数,需要再调用一次才能执行。
一、实现call
Function.prototype.myCall = function(context, ...args) {
if(typeof this !=='function') {
throw new TypeError('不是函数')
}
context = context || window
context.fn = this
const res = context.fn(...args)
delete context.fn
return res
}
二、实现apply
Function.prototype.myApply = function(context, ...args) {
if(typeof this !=='function') {
throw new TypeError('不是函数')
}
context = context || window
context.fn = this
args = args && args[0] || []
const res = context.fn(...args)
delete context.fn
return res
}
三、实现bind
Function.prototype.myBind = function(context, ...args) {
return (...args1) => {
context = context || window
return this.apply(context, [...args, ...args1])
}
}