为了账号安全,请及时绑定邮箱和手机立即绑定

被这个this指向弄晕了,求请教

被这个this指向弄晕了,求请教

守着一只汪 2019-05-23 18:16:20
functionRouter(){this.routes={};this.currentUrl='';}Router.prototype.route=function(path,callback){this.routes[path]=callback||function(){};}Router.prototype.refresh=function(){this.currentUrl=location.hash.slice('1')||'/';this.routes[this.currentUrl]();}Router.prototype.init=function(){window.addEventListener('load',this.refresh.bind(this),false);window.addEventListener('hashchange',this.refresh.bind(this),false);}window.Router=newRouter();window.Router.init();varcontent=document.querySelector('body');//changePageanythingfunctionchangeBgColor(color){content.style.backgroundColor=color;}Router.route('/',function(){changeBgColor('red')})Router.route('/blue',function(){changeBgColor('blue')})Router.route('/green',function(){changeBgColor('green')})问题就在于window.addEventListener('load',this.refresh.bind(this),false);这句话中this.refresh.bind(this),弄晕了,换成this.refresh.apply(this)和call都会报错,有人能帮我来理清这个this指向的顺序吗?以及为什么不能使用apply和call
查看完整描述

2 回答

?
BIG阳

TA贡献1859条经验 获得超6个赞

this.refresh.apply(this)是改变作用域并执行this.refresh.bind(this)是改变作用域并返回新函数(未执行)这里的this.refresh.bind(this)是改变addEventListener的this将其指向Router,因为事件的this指向事件的绑定者,这里是window
                            
查看完整回答
反对 回复 2019-05-23
?
阿晨1998

TA贡献2037条经验 获得超6个赞

call和apply会自动执行函数,而bind不会
window.addEventListener里的第二个参数是一个函数
用call和apply的话得到的就是执行完的结果,也就是函数返回值,你的refresh没有返回值(return),得到的也就是undefined,所以会报错啦
                            
查看完整回答
反对 回复 2019-05-23
  • 2 回答
  • 0 关注
  • 466 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号