javascript的apply、call、bind实现
Function.prototype.myCall=function(context,...arg){
let ctx=context||window
let uuid= Symbol()
ctx[uuid]=this
let result=ctx[uuid](...arg)
return result
}
Function.prototype.myApply=function(context,arg){
let ctx=context||window
let uuid= Symbol()
ctx[uuid]=this
let result=ctx[uuid](...arg)
delete ctx[uuid]
return result
}
Function.prototype.myBind=function(context,arg){
const fn =this
return function(...innerArgs){
return fn.apply(context,arg.concat(innerArgs))
}
}
const obj={
name:'jack'
}
function greet(args){
console.log('xx',this,args)
}
greet()
greet.apply(obj,['apply rose'])
greet.call(obj,'call rose')
let f=greet.bind(obj)
f('bind')
输出
“xx” [object Window] undefined
“xx” Object { name: “jack” } “apply rose”
“xx” Object { name: “jack” } “call rose”
“xx” Object { name: “jack” } “bind”