87,919
社区成员
发帖
与我相关
我的任务
分享
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();//一秒后报错
主要问题是出在window.setTimeout身上 window.setTimeout(this.core...,XXX);这会这个this的上下文指向了window全局对象 所以this.core就不对了
这里就用闭包 将this一开始就保存到了_me的变量里 然后_me指向的是对象 所以就可以用_me.core来操作了
感觉像是闭包的问题啊,这个this,指向的是什么?是DoTest吗
<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>