apply、call、bind 的实现
apply
参数:(this, Array), 需要绑定的 this,数组或者类数组对象
返回值:函数调用指定 this 的结果
Function.prototype.myApply = function (thisValue, arg = []) {
thisValue = [undefined, null].includes(thisValue) ? window : thisValue
if (!Array.isArray(arg) && !Array.isArray(Array.from(arg))) {
throw new Error('arguments is not array')
}
thisValue.fn = this
const result = thisValue.fn(...Array.from(arg))
delete thisValue.fn
return result
}
call
参数:(this, arr1,arr2,...), 需要绑定的 this,参数列表
返回值:函数调用指定 this 的结果
Function.prototype.myCall = function (thisValue) {
thisValue = [undefined, null].includes(thisValue) ? window : thisValue
const args = [...arguments].slice(1)
thisValue.fn = this
const result = thisValue.fn(..args)
delete thisValue.fn
return result
}
bind
参数:(this, arr1,arr2,...), 需要绑定的 this,参数列表
兼容
new关键字返回值:返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。
Function.prototype.myBind = function (thisValue) {
var fn = this
var arg = Array.prototype.slice.call(arguments, 1)
return function Fn() {
const newArg = Array.prototype.slice.call(arguments)
return fn.apply(
this instanceof Fn ? new fn(...arguments) : thisValue,
arg.concat(...newArg)
)
}
}