首页  >  问答  >  正文

javascript - js一道面试题。貌似闭包,上下文,函数调用,声明,setTimeout()

遇到这样一道题,一个函数内,有两个alert函数,第二次alert需要在第一次alert2000ms后调用

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

搜了一下答案发现无关闭包,只是有关上下文,但不是特别明白,大神求带!!!!
我最后的解决方法是在34行间插入 var this.msg= msg; 在 10.11行插入 aa.shout();
不知有没有更好的(优雅-。-)解决方法?

抱歉刚刚没描述清楚,这道题的本意应该是调用aa.waitAndShout()呼出两个间隔两秒的alert
**我想请教的是这道题要怎么改,才能达到这种效果
最后或者是我理解错了?还是就是考察this指针的用法

巴扎黑巴扎黑2749 天前1128

全部回复(11)我来回复

  • 黄舟

    黄舟2017-04-11 10:43:23

        var Obj=function(msg){
            this.msg=msg; 
            var that = this;// 修改部位
            this.shout=function(){
                alert(that.msg);// 修改部位
            };
            this.waitAndShout=function(){
                setTimeout(that.shout,2000);// 修改部位
            };
        }

    缓存一下this

    回复
    0
  • 取消回复