[英]why settimeout() anonymous function not call the function in javascript?
[英]Why is an anonymous function required to preserve “this” using setTimeout
我已经多次使用setTimeout
传递一个函数作为参考,例如
setTimeout(someFunction, 3000);
在某些情况下,保存的值this
我已经将其分配到前手的变量,但不明白为什么下面不工作:
var logger = {
log: function() {
var that = this;
console.log(that.msg);
setTimeout(that.log, 3000);
},
msg: "test"
};
logger.log();
但是,使用匿名函数可以正常工作:
var logger = {
log: function() {
var that = this;
console.log(that.msg);
setTimeout(function() { that.log() }, 3000);
},
msg: "test"
};
这不起作用,因为setTimeout
使用this
值作为全局对象而不是父对象调用函数。 你传递一个值到setTimeout
功能-它不知道它是如何被访问的,因此不能用正确的调用它this
值(不像正常的变量,值this
当你调用函数只被确定,除非this
已经被绑定到使用特定值Function.prototype.bind
)。
通过改变一个匿名函数,您使用的封闭访问的价值that
,作为一种价值(函数的变量范围被设定,当它被定义,而不是当它运行)呼吁时也是如此。
这就像你做这样的事情:
var a = { b: function () { return this.foo; }, foo: 'proper' };
function test(arg) {
return arg();
}
var foo = 'random';
console.log(a.b()); // proper
console.log(test(a.b)); // random
还有使用一个相关的问题this
与setTimeout
: 传递正确的“这个”背景下的setTimeout回调?
因为在第一种情况下,你只引用功能log
那是内that
物体,但其关系that
丢失。 可以把它想象成setTimeout
直接调用存储的内存地址中的log
方法和全局上下文。
在第二个例子但是你来自全球范围内,但首先that
是抬头,事后log
其与上下文称为然后that
。
可以认为setTimeout具有以下结构:
var setTimeout = function (func, time) {
someWaitMechanism(time, function () { //this is called after the timeout
func.call(null); //calls func with global scope
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.