如何自定义实现call、apply、bind方法呢
1 实现call方法
Function.prototype.myCall = function (context,...arg) {
context = typeof context === 'object' ? context : window
let key = Symbol() //防止覆盖原有属性
context[key] = this //this是该函数
context[key](...arg) //执行函数
delete context[key]
}
function fn(x,y){
console.log(this.name)
console.log(x+y)
}
let obj = {
name: 'lx'
}
fn.myCall(obj,12,3)
2 实现apply方法
Function.prototype.myApply = function (context,arg) {
context = typeof context === 'object' ? context : window
let key = Symbol() //防止覆盖原有属性
context[key] = this //this是该函数
context[key](...arg) //执行函数
delete context[key]
}
function fn(x,y){
console.log(this.name)
console.log(x+y)
}
let obj = {
name: 'lx'
}
fn.myApply(obj,[12,3])
3 实现bind方法
Function.prototype.myBind = function (context) {
context = typeof context === 'object' ? context : window
let key = Symbol()
context[key] = this
let argArr = []
for(let i = 1; i < arguments.length; i++){
argArr.push(arguments[i])
}
let fnBind = function(){
context[key].call(context,...argArr)
}
return fnBind
}
function fn(x,y){
console.log(this.name)
console.log(x+y)
}
let obj = {
name: 'lx'
}
fn.myBind(obj)()
- 本文作者: étoile
- 版权声明: 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。转载请注明出处!