什么时候调用带括号 () 和不带括号 () 的函数?

When to call function with and without parenthesis brackets ()?

我正在学习教程 here,遇到了一些我不完全理解的语法。

我希望每次滚动时,console.log 记录“你好”。

function moveCamera() {
  console.log("hello");
}

document.body.onscroll = moveCamera()
function moveCamera() {
  console.log("hello");
}

document.body.onscroll = moveCamera

在第一个示例中,console.log("hello") 运行一次,但之后再也不会运行,无论我是否滚动。

在第二个示例中,每次滚动时代码都会运行并记录“hello”。

我了解到对于第二个示例,moveCamera 传递了函数的副本,使函数看起来有点像这样:

document.body.onscroll = function () {
  console.log("Hello");
}

但是,我仍然不明白为什么用括号 调用 moveCamera() 不会 工作并产生 不需要的功能。

编辑:我设计了一种非常简单的方法来理解何时使用括号,何时不使用。我会把它放在这里,因为我的问题被标记为重复。

没有括号的例子

// Example 1: If you are assigning, use reference
document.body.onscroll = moveCamera;
// Example 2: If you are event listening, use reference
document.body.addEventListener("scroll", moveCamera);

带括号的例子

// Example 1: If you are executing on a single line alone, use call.
...
moveCamera()
...
// Example 2: If you want to repeatedly call this function, 
// like I did in my example, use a loop or an animate() function.
// @note this is a THREE.js specific example
function animate() {
  requestAnimationFrame(animate);
  moveCamera()
  renderer.render(scene,camera);
}

您应该在函数中放置一个字符串。不是函数本身,因为无论函数 return 是什么,它都会 return。此外,我建议使用 setAttribute() 函数:

document.body.setAttribute("onscroll", "moveCamera()");

  • 假设你有这个功能,使用不带引号的moveCamera()

function moveCamera() {
  return "console.log('Hello')";
}

document.body.setAttribute("onscroll", moveCamera());
body {
  height: 200vh;
}
<body></body>

  • 使用带引号的moveCamera()作为字符串:

function moveCamera() {
  console.log("Hello");
}

document.body.setAttribute("onscroll", "moveCamera()");
body {
  height: 200vh;
}
<body></body>

如果您调用 moveCamera,您分配的是 moveCamera 函数返回的值,而不是函数本身。

以下示例对此进行了说明:

function a(){
  return "b";
}
var a = a;
var b = a();

console.log("a = "+a);
console.log("b = "+b);