道招

this指针变更,重新bind

如果您发现本文排版有问题,可以先点击下面的链接切换至老版进行查看!!!

this指针变更,重新bind

这是一个面试题, [code lang="javascript"] 1 . var Obj=function(msg){ 2 . this.msg=msg; 3 . this.shout=function(){ 4 . alert(this.msg); 5 . }; 6 . this.waitAndShout=function(){ 7 . setTimeout(this.shout,2000); 8 . }; 9 . } 10. var aa=new Obj("abc"); 11. aa.waitAndShout(); //2s后undefined [/code] 按照上述代码的结果就是2秒后弹出alert,内容是"undefined",而面试官的意思是怎么简单的让2秒后的alert弹出的内容为abc。 有网友给出如下解答,用that来指向原来的this,当然that不是什么js关键字,方法还是很实用的。 [code lang="javascript"] var Obj=function(msg){ this.msg=msg; var that = this; this.shout=function(){ alert(that.msg); }; this.waitAndShout=function(){ setTimeout(this.shout,2000); }; } var aa=new Obj("abc"); aa.waitAndShout(); //2s后 [/code] 也有大神提出了别样的解决方案,只用改setTimeout那一句。 [code lang="javascript"] setTimeout(this.shout.bind(this),2000); [/code] 同时TA是这样回复的--此题关键在于: 将 this.shout 传给 setTimeout 后,shout 的 this 就不是 aa 而是 window 了,因此要用 bind 重新绑定。
更新时间:
上一篇:下一篇:

相关文章

关注道招网公众帐号
友情链接
消息推送
道招网关注互联网,分享IT资讯,前沿科技、编程技术,是否允许文章更新后推送通知消息。
允许
不用了