<script type="text/javascript">
window.onload=function()
{
var m=new main('aaaa');
m.run();
}
var main=function(param)
{
this.param=param;
this.run=function()
{
setTimeout(this.Change,3000);
}
this.Change=function()
{
alert(this.param);
}
}
</script>
这个代码看起来很清晰,但是会报错,原因我想大概就是在隔了三秒执行Change方法时找不到this.param,this.Change的this就指向了window,不是实例m了,整了半天没有整明白,没办法只好上网求助,结果有高手给除了解决方法,修改this指针。再来看新代码:window.onload=function()
{
var m=new main('aaaa');
m.run();
}
var main=function(param)
{
this.param=param;
this.run=function()
{
setTimeout(this.Change,3000);
}
this.Change=function()
{
alert(this.param);
}
}
</script>
<script type="text/javascript">
window.onload=function()
{
var m=new main('aaaa');
m.run();
}
var main=function(param)
{
this.param=param;
this.run=function()
{
var self=this;
setTimeout(self.Change.setThis(self),3000);
}
this.Change=function()
{
alert(this.param);
}
Function.prototype.setThis = function(object)
{
var __method = this;
return function()
{
__method.apply(object, arguments);
} ;
};
}
</script>
window.onload=function()
{
var m=new main('aaaa');
m.run();
}
var main=function(param)
{
this.param=param;
this.run=function()
{
var self=this;
setTimeout(self.Change.setThis(self),3000);
}
this.Change=function()
{
alert(this.param);
}
Function.prototype.setThis = function(object)
{
var __method = this;
return function()
{
__method.apply(object, arguments);
} ;
};
}
</script>
其中添加了一段修改指正的代码,修改指针代码:
Function.prototype.setThis = function(object)
{
var __method = this;
return function()
{
__method.apply(object, arguments);
} ;
};
使用的时候要定义一个变量self=this; 用self来调用。最主要的是不理解apply到底是做啥子用的,只能先记下来,以后慢慢理解!{
var __method = this;
return function()
{
__method.apply(object, arguments);
} ;
};