code_cc
2019-02-12 22:26:56浏览 1831
//call
Function.prototype.mycall=function(context){
if(typeof this!=='function'){
throw new TypeError('Error')
}
context=context||window
context.fn=this//给 context 创建一个fn属性,并将值设置为需要调用的函数
const args=[...arguments].slice(1)//拆分参数
const result=context.fn(...args)
delete context.fn//删除属性
return result
}
//apply
Function.prototype.myapply=function(context){
if(typeof this!=='function'){
throw new TypeError('Error')
}
context=context||window
context.fn=this
if (arguments[1]) {
result = context.fn(...arguments[1])
}else {
result = context.fn()
}
delete context.fn//删除属性
return result
}
//bind
Function.prototype.mybind=function(context){
if(typeof this!=='function'){
throw new TypeError('Error')
}
const _this=this
const args=[...arguments].slice(1)
return function F(){ //new 调用
if(this instanceof F){
return new _this(...args,...arguments)
}
return _this.apply(context,args.concat(...arguments))}}