setTimeout中的两个this到底指向谁??为了便于区分,我们把setTimeout调用环境下的this称之为第一个this,把延迟执行函数中的this称之为第二个this,并在代码注释中标出来,方便您区分。先说得出的结论:第一个this的指向是需要根据上下文来确定的,默认为window;第二个this就是指向window。

1
2
3
4
5
6
7
8
9
10
function Foo() {
this.value = 42;
this.method = function() {
// this 指向全局对象
alert(this) // 输出window 第二个this
alert(this.value); // 输出:undefined 第二个this
};
setTimeout(this.method, 500); // this指向Foo的实例对象 第一个this
}
new Foo();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var value=33;

function Foo() {
this.value = 42;
this.method = function() {
// this 指向全局对象
alert(this) // 输出window 第二个this
alert(this.value); // 输出:33 第二个this
};
setTimeout(this.method, 500); // 这里的this指向Foo的实例对象 第一个this
}
new Foo();

<!-- 等价于 -->
var value=33;

function Foo() {
this.value = 42;
setTimeout(function(){alert(this);alert(this.value)}, 500); // 先后输出 window 33 这里是第二个this
}
new Foo();

代码验证

1
2
3
4
5
6
7
8
9
10
var test = "in the window";

setTimeout(function() {alert('outer ' + test)}, 0); // 输出 outer in the window ,默认在window的全局作用域下

function f() {
var test = 'in the f!'; // 局部变量,window作用域不可访问
setTimeout('alert("inner " + test)', 0); // 输出 inner in the window, 虽然在f方法的中调用,但执行代码(字符串形式的代码)默认在window全局作用域下,test也指向全局的test
}

f();

在f方法中,setTimeout中的test的值是外层的test,而不是f作用域中的test。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var test = "in the window";

setTimeout(function() {alert('outer' + test)}, 0); // outer in the window ,没有问题,在全局下调用,访问全局中的test

function f() {
var test = 'in the f!';
setTimeout(function(){alert('inner '+ test)}, 0); // inner in the f! 有问题,不是说好了执行函数中的this指向的是window吗?那test也应该对应window下 // 的值才对,怎么test的值却是 f()中的值呢????
}

f();

<!-- 等价于 -->
var test = "in the window";

setTimeout(function() {alert('outer ' + test)}, 0); // in the window

function f() {
var test = 'in the f!';

function ff() {alert('inner ' + test)} // 能访问到f中的test局部变量

setTimeout(ff, 0); // inner in the f!
}

f();

博文链接[http://www.geekcome.com/content-10-2517-1.html]