foo.Mycall(obj,1,2,3)
Function.prototype.Mycall=function(target,...args){
if(typeof this!=='function'){
throw new TypeError('this is not a function')
}
// 判断target是否是对象
if(target==null||target==undefined){
target=window
}
if(typeof target!=='object'){
target=Object(target)
}
// 把this作为target的方法
let key=new Symbol()
target[key]=this;
let res=target[key](...args)
delete target[key]
return res
}
apply和call差不多,都是直接返回函数执行的结果
区别:apply传入的参数是数组
foo.Myapply(obj,[1,2,3])
Function.prototype.Myapply=function(target,args){
if(typeof this!=='function'){
throw new TypeError('this is not a function')
}
if(target==null||target===undefined){
target=window
}
if(typeof target!=='object'){
target=Object(target)
}
let key=new Symbol()
target[key]=this;
let res=target[key](...args)
delete target[key]
return res
}
bind:
Function.prototype.bind=function(context,...args){
if(typeof this!=='function'){
throw new Error('this is not a function')
}
if(context==null||context==undefined){
context=window
}
if(context!=='object'){
context=Object(context)
}
let key=new Symbol()
context[key]=this;
return function(...newargs){
let res=context[key](...args,...newargs)
delete context[key]
return res
}
}