call,apply,bind方法在哪
Function.prototype.call
Function.prototype.apply
Function.prototype.bind
实现call方法
// 在Function.prototype上添加一个myCall方法
Function.prototype.myCall = function (obj, ...arr) {
// 避免传入的obj是null
const newObj = obj || window
newObj.p = this
const result = newObj.p(...arr)
delete newObj.p
return result
}
实现apply方法
大致与call方法实现相同,注意apply的第二个参数是数组
// 在Function.prototype上添加一个myApply方法
Function.prototype.myApply = function (obj, arr) {
const newObj = obj || window
newObj.p = this
const result = newObj.p(...arr)
delete newObj.p
return result
}
实现bind方法
// 在Function.prototype上添加一个myBind方法
Function.prototype.myBind = function (obj, ...arr1) {
const that = this
const newf = function (...arr2) {
// 处理new bind返回的函数的问题
that.myCall(this instanceof newf ? this : obj, ...arr1, ...arr2)
}
// 接上原型链
newf.prototype = Object.create(that.prototype)
return newf
}