为什么用括号调用setTimeout不会启动新的callstack? [英] Why does calling setTimeout with parenthesis not start a new callstack?

查看:171
本文介绍了为什么用括号调用setTimeout不会启动新的callstack?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在调试器触发时有一个新的调用堆栈(jsfiddle 此处

The following code has a new callstack when the debugger fires in d (jsfiddle here)

function c() {
    setTimeout( d, 1000 );
}

function d() {
    debugger;   
}

c();

如果我们修改代码使用 setTimeout(d(),1000) ; 哪个有括号(括号:)

If we modify the code to use setTimeout( d(), 1000 ); which has brackets (parenthesis:)

function c() {
    setTimeout( d(), 1000 );
}

function d() {
    debugger;   
}

c();

然后callstack同时有c()和d()(jsfiddle 这里)。为什么?

then the callstack has both c() and d() (jsfiddle here). Why?

推荐答案

你没有传递 setTimeout 函数<$ c第二个例子中的$ c> d ;你正在传递 d(),这是调用 d 的结果。

You are not passing setTimeout the function d in the second example; you are instead passing d(), which is the result of calling d.

调用 d 的结果是 undefined ,因为它什么都不返回,转换为字符串undefined,然后是 eval ed,正在做......没什么。

The result of calling d is undefined since it returns nothing, which converts to the string "undefined", which is then evaled, doing... precisely nothing.

关于callstacks,因为你在中调用 d c ,这就是你在callstack中看到 c 的原因。为了澄清,你的第二个例子与

With regard to callstacks, since you are calling d inside of c, that is why you see c in the callstack. To clarify, your second example is the same as

function c() {
    var temp = d();
    setTimeout(temp, 1000);
}

function d() {
    debugger;   
}

c();

这篇关于为什么用括号调用setTimeout不会启动新的callstack?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆