我何时使用括号,何时不使用括号? [英] When do I use parenthesis and when do I not?

查看:128
本文介绍了我何时使用括号,何时不使用括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么说:

var myFunction = function() {
   setTimeout(myFunction, 1000);
}
myFunction();

为什么函数调用 setTimeout 不需要括号,但最后一行呢?

Why does the function call in the setTimeout not require a parenthesis, but the last line does?

推荐答案

myFunction 是一个函数

myFunction()调用函数并产生函数返回的任何值。

myFunction() calls the function and yields whatever value the function returns.

setTimeout的目的是在经过一段时间后运行代码。你只需要将函数传递给它(因此setTimeout本身可以在适当的时候调用函数),因为如果在将函数传递给setTimeout之前调用函数(带括号),它将执行 now 而不是之后1秒。

The purpose of setTimeout is running code after some time elapses. You need to pass just the function to it (so setTimeout can itself call the function when appropriate) because if you called the function (with the parenthesis) before passing it to setTimeout it would execute now instead of after 1 second.

这篇关于我何时使用括号,何时不使用括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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