对象的方法如何外调?

WM_JAWIN 2009-11-06 02:51:19

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做了一个简单的测试对象.请问一下对象的方法,应该怎么回调?
...全文
99 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
flopgiggle 2009-11-08
  • 打赏
  • 举报
回复
var _self = this;
window.setTimeout(function(){_self.core()},1000);
mingyue201314 2009-11-07
  • 打赏
  • 举报
回复
就是说在上面的问题中,我要调用 function(){alert(this.msg);} 这个函数的话,必须要重新写一个函数,把它通过window.setTimeout 包起来吗?
不能直接像调用Core吗? 为什么要这样做呢?
能给我详细解释下吗?我是刚学Javascript的
谢谢了
zhangshaolongjj 2009-11-07
  • 打赏
  • 举报
回复
这个 this指的是window
Click_Me 2009-11-07
  • 打赏
  • 举报
回复

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

mingyue201314 2009-11-07
  • 打赏
  • 举报
回复
为什么不能直接调用 this.core=function(){alert(this.msg);}这个方法呢?
对于下面这段代码中的
this.DoTest=function()
{
var _me = this;
window.setTimeout(function(){ _me.core();},1000);
}
又是什么意思呢?
zhouxiaobo123 2009-11-07
  • 打赏
  • 举报
回复
延时后是不是this就不存在了,所以好放在变量里?
msdnlu 2009-11-06
  • 打赏
  • 举报
回复
this指的是test这个call对象
Click_Me 2009-11-06
  • 打赏
  • 举报
回复

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

对啊 这个就是个闭包的问题啊
xiaofan_sap 2009-11-06
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 click_me 的回复:]
JScript code<script type="text/javascript"><!--function test(){this.msg="for test";this.core=function(){alert(this.msg);}this.DoTest=function()
{var _me=this;
window.setTimeout(fun?-
[/Quote]

感觉像是闭包的问题啊,这个this,指向的是什么?是DoTest吗
gkw521 2009-11-06
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 wtcsy 的回复:]
cuole
var _self = this;
window.setTimeout(function(){_self.core()},1000);
[/Quote]
正解,俺来拿分~
Click_Me 2009-11-06
  • 打赏
  • 举报
回复

<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>
wtcsy 2009-11-06
  • 打赏
  • 举报
回复
cuole
var _self = this;
window.setTimeout(function(){_self.core()},1000);
wtcsy 2009-11-06
  • 打赏
  • 举报
回复
var _self = this;
window.setTimeout(function(){_self.core},1000);

87,919

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧