call重写
Function.prototype.call2=function(_this,...args){
let fun=this
let ctx=_this
ctx.myfun=fun
let res=ctx.myfun(...args)
delete ctx.myfun
return res
}
function sayHello(a,b) {
console.log(this.hello+a+b)
}
let chineseMan = {
hello: '你好啊'
}
sayHello.call2(chineseMan,1,2)
let englishMan = {
hello: 'how are you'
}
sayHello.call2(englishMan,3,4)
apply重写
Function.prototype.apply2=function(_this,array){
let fun=this
let ctx=_this
ctx.myfun=fun
let res=ctx.myfun(...array)
delete ctx.myfun
return res
}
function sayHello(a,b) {
console.log(this.hello+a+b)
}
let chineseMan = {
hello: '你好啊'
}
sayHello.apply2(chineseMan,[1,2])
let englishMan = {
hello: 'how are you'
}
sayHello.apply2(englishMan,[3,4])
bind重写
Function.prototype.bind2=function(_this,...outerargs){
let fun=this
let ctx=_this
function inner(...innerargs){
let args=[...outerargs,...innerargs]
ctx.myfun=fun
let res=ctx.myfun(...args)
delete ctx.myfun
return fun
}
return inner
}
function sayHello(a,b) {
console.log(this.hello+a+b)
}
let chineseMan = {
hello: '你好啊'
}
sayHello.bind2(chineseMan,1,2)()
let englishMan = {
hello: 'how are you'
}
sayHello.bind2(englishMan,3,4)()