gpt4 book ai didi

javascript - setTimeout 的执行上下文(JavaScript)

转载 作者:行者123 更新时间:2023-11-30 07:26:17 25 4
gpt4 key购买 nike

1) 谁能说明 setTimeout 在执行线程方面的工作原理。

考虑:

function foo() { alert('foo'); }
function bar() { alert('bar'); }
setTimeout(foo,1000);
bar();

function foo() { alert('foo'); setTimeout(foo,1000); }
function bar() { alert('bar'); }
setTimeout(foo,1000);
bar();

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

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

function foo() { alert('foo'); setTimeout(foo,1000); }
function bar() { alert('foo'); setTimeout(bar,1000); }
setTimeout(foo,1000);
setTimeout(bar,1000);

2) 谁能解释为什么“这个”对象在 setTimeout 中不起作用,以及我们可以做些什么来解决这个问题?

最佳答案

一定要阅读@DaveAnderson 建议的文章。

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

setTimeout(arg, timeout)

如果 arg 是一个字符串,那么它被视为要执行的源代码。这和 eval() 一样糟糕。避免它。

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

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

var t = new Test();

打印 x: undefined.

所以你想做的是:

function foo() { alert('foo'); }
setTimeout('foo()', 1000);

或更好:

setTimeout(foo, 1000);

要固定函数的上下文,请使用绑定(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();

或手动执行:

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();

关于javascript - setTimeout 的执行上下文(JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13870049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com