1、setTimeout中的延迟执行代码中的this永远都指向window
setTimeout("alert(this)", 1)
// 对象中函数执行
var obj = {
say: function() {
setTimeout("alert('in obj ' + this)", 0)
}
}
obj.say();
对象中的匿名函数
// 对象中的匿名函数
var obj = {
say: function() {
setTimeout(function(){alert(this)}, 0)
}
}
obj.say();
函数方式引入执行
function talk() {
alert(this);
}
var obj = {
say: function() {
setTimeout(talk, 0)
}
}
obj.say();
2、setTimeout(this.method, time)这种形式中的this,是根据上下文来判断的,默认为全局作用域,但不一定总是处于全局下,具体问题具体分析
- setTimeout环境下的this:setTimeout(this.method, time),这个this根据环境来定
延迟函数内执行环境的this:setTimeout(function(){console.log(this);}, time),这个this永远指向window
var value=33;
function Foo() {
this.value = 42;
this.method = function() {
alert(this) // [object Window]
alert(this.value); // 33
};
setTimeout(this.method, 500);
}
new Foo();
3、setTimeout(匿名函数, time)这种形式下,匿名函数中的变量也需要根据上下文来判断,具体问题具体分析。
// 类似于promise的reslove执行
var test = "in the window";
setTimeout(function() {alert('outer ' + test)}, 0); // outer in the window
function f() {
var test = 'in the f!';
function ff() {alert('inner ' + test)} // inner in the f!
setTimeout(ff, 0);
}
f();
4、setTimeout方法是挂在window对象下的,而超时调用的代码都是在全局作用域中执行的,因此函数中this的值在非严格模式下指向window对象,在严格模式下是undefined