function  test(){
    
        this.msg="for test";
        this.core=function{alert(this.msg);}
        this.DoTest=function()
        {
/*这里隐藏了N多代码*/
           window.setTimeout(/*这里应该怎么调用 this.core??*/,1000);
/*这里隐藏了N多代码*/
        }
    
    }
    var t=new test();
    t.core();//这样调用正常
    t.DoTest();//一秒后报错
像上面代码所示,用js做了一个简单的测试对象.请问一下对象的方法,应该怎么回调?

解决方案 »

  1.   

    var _self = this;
    window.setTimeout(function(){_self.core},1000);
      

  2.   

    cuole
    var _self = this; 
    window.setTimeout(function(){_self.core()},1000); 
      

  3.   


    <script type="text/javascript">
       <!--
       function  test(){
        
            this.msg="for test";
            this.core=function(){alert(this.msg);}
            this.DoTest=function()
            {
       var _me = this;
               window.setTimeout(function(){ _me.core();},1000);        }
        
        }
        var t=new test();
        t.core();
        t.DoTest();   //-->
       </script>
      

  4.   


    感觉像是闭包的问题啊,这个this,指向的是什么?是DoTest吗
      

  5.   


    感觉像是闭包的问题啊,这个this,指向的是什么?是DoTest吗对啊 这个就是个闭包的问题啊 
      

  6.   

    为什么不能直接调用    this.core=function(){alert(this.msg);}这个方法呢?
    对于下面这段代码中的
            this.DoTest=function()
            {
               var _me = this;
               window.setTimeout(function(){ _me.core();},1000);
            }
    又是什么意思呢?
      

  7.   


    主要问题是出在window.setTimeout身上 window.setTimeout(this.core...,XXX);这会这个this的上下文指向了window全局对象 所以this.core就不对了 
    这里就用闭包 将this一开始就保存到了_me的变量里 然后_me指向的是对象 所以就可以用_me.core来操作了
      

  8.   

    就是说在上面的问题中,我要调用 function(){alert(this.msg);} 这个函数的话,必须要重新写一个函数,把它通过window.setTimeout 包起来吗?
    不能直接像调用Core吗? 为什么要这样做呢?
    能给我详细解释下吗?我是刚学Javascript的
    谢谢了
      

  9.   

    延时后是不是this就不存在了,所以好放在变量里?
      

  10.   

    var _self = this; 
    window.setTimeout(function(){_self.core()},1000);