我试图以750毫秒的延迟调用实例的方法。问题是,它不起作用。我已经读过setInterval和对象存在某种问题,所以可能还有setTimeout的问题。
说我有这个:
function App()
{
this.doFoo = function (arg)
{
alert("bar");
}
}
window.app = new App();
setTimeout('app.doFoo(arg)', 750);//doesn't work
app.doFoo(arg); //works
有解决方法吗?如何将实例和函数传递给setTimeout?
答案 0 :(得分:2)
试试这样:
function App()
{
this.doFoo = function (arg) {
alert(arg);
}
}
window.app = new App();
window.setTimeout(function() {
window.app.doFoo('arg');
}, 750);
答案 1 :(得分:2)
我认为之前的回答需要一些调整。它正在设置一个你正在调用的全局变量;如果你真的想调用你的“课堂”的一个实例,试试这个。
function App(message){
this.name = 'instance';
var self = this;
var x = setTimeout(function(){self.doFoo(message, x);}, 750);
}
App.prototype.name = 'proto';
//creating the function on the prototype is more efficient since it is only created once. if you do 'this.doFoo = function(){}' it's created for every instance of the function taking more memory.
App.prototype.doFoo = function(arg, timer){
clearTimeout(timer);
alert(this.name +' ' + arg)
}
var x = new App("hello world");
//should output ("instance hello world");