首页 > 解决方案 > 何时调用带和不带括号 () 的函数?

问题描述

我在这里完成了一个教程,并遇到了一些我不完全理解的语法。

我希望每次滚动时,console.log 都会记录“hello”。

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

标签: javascriptthree.js

解决方案


您应该在函数中放置一个字符串。不是函数本身,因为它会返回函数返回的任何内容。另外,我建议使用该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>


推荐阅读