Muk*_*was 1 javascript json object
这应该引用对象本身但在下面的代码中为什么它的行为不同?
var x = 4,
obj = {
x: 3,
bar: function() {
var x = 2;
setTimeout(function() {
var x = 1;
alert(this.x);
}, 1000);
}
};
obj.bar();
Run Code Online (Sandbox Code Playgroud)
警报为什么4
而不是3
?
内部setTimeout
回调this
是指窗口对象,因此它检索在全局上下文中定义的变量.
您可以通过使用Function#bind
方法绑定此上下文来使其工作.
var x = 4,
obj = {
x: 3,
bar: function() {
var x = 2;
setTimeout(function() {
var x = 1;
alert(this.x);
}.bind(this), 1000);
}
};
obj.bar();
Run Code Online (Sandbox Code Playgroud)
或者使用局部变量来缓存对this
内部回调函数的引用并使用它.
var x = 4,
obj = {
x: 3,
bar: function() {
var x = 2,
that = this;
setTimeout(function() {
var x = 1;
alert(that.x);
}, 1000);
}
};
obj.bar();
Run Code Online (Sandbox Code Playgroud)
另请参阅MDN文档:"this"问题
归档时间: |
|
查看次数: |
59 次 |
最近记录: |