call 简易实现
标签:
JavaScript
//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))}}点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦