setTimeout(JavaScript)的执行上下文

Ton*_*ark 1 javascript settimeout

1)有人可以说明setTimeout如何在执行线程方面工作.

考虑:

function foo() { alert('foo'); }
function bar() { alert('bar'); }  
setTimeout(foo,1000);
bar();
Run Code Online (Sandbox Code Playgroud)

要么

function foo() { alert('foo'); setTimeout(foo,1000); }
function bar() { alert('bar'); }  
setTimeout(foo,1000);
bar();
Run Code Online (Sandbox Code Playgroud)

要么

function foo() { alert('foo'); setTimeout(foo,1000); }
function bar() { /* an execution that runs with unknown time */ }  
setTimeout(foo,1000);
bar();
Run Code Online (Sandbox Code Playgroud)

要么

function foo() { alert('foo'); setTimeout(foo,1000); }
function bar() { /* some ajax call that reply with unknown time */ }  
setTimeout(foo,1000);
bar();
Run Code Online (Sandbox Code Playgroud)

要么

function foo() { alert('foo'); setTimeout(foo,1000); }
function bar() { alert('foo'); setTimeout(bar,1000); }  
setTimeout(foo,1000);
setTimeout(bar,1000);
Run Code Online (Sandbox Code Playgroud)

2)有人可以解释为什么"this"对象在setTimeout中不起作用以及我们可以做些什么来解决这个问题?

Ste*_*fan 8

请阅读@DaveAnderson建议的文章.

至于其他东西,setTimeout/setInterval有两种形式:

setTimeout(arg, timeout)
Run Code Online (Sandbox Code Playgroud)

如果arg是一个字符串,那么它被视为要执行的源代码.这与eval()一样糟糕.躲开它.

如果arg是一个函数,那么它在全局上下文中执行:

var Test = function () {
    this.x = 1;
    setTimeout(function () {
        console.log('x: ' + this.x);
    }, 10);
};

var t = new Test();
Run Code Online (Sandbox Code Playgroud)

打印x:未定义.

所以你想要做的是:

function foo() { alert('foo'); }
setTimeout('foo()', 1000);
Run Code Online (Sandbox Code Playgroud)

或更好:

setTimeout(foo, 1000);
Run Code Online (Sandbox Code Playgroud)

要修复函数的上下文,请使用bind方法:

var Test = function () {
    this.x = 1;
    var f = function () {
        console.log('x: ' + this.x);
    };
    setTimeout(f.bind(this), 10);         // use this as the context
};

var t = new Test();
Run Code Online (Sandbox Code Playgroud)

或者手动完成:

var Test = function () {
    this.x = 1;
    var that = this;
    setTimeout(function () {
        console.log('x: ' + that.x);     // closure: closing over that
    }, 10);
};

var t = new Test();
Run Code Online (Sandbox Code Playgroud)