javascript - 何时调用带和不带括号 () 的函数?
问题描述
我在这里完成了一个教程,并遇到了一些我不完全理解的语法。
我希望每次滚动时,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);
}
解决方案
您应该在函数中放置一个字符串。不是函数本身,因为它会返回函数返回的任何内容。另外,我建议使用该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>
推荐阅读
- .net - 是否可以在项目 .Net framework 3.5 中引用 Identity.Model 库?
- html - 为什么 HTML 有这么多颜色值(RGB、HEX、HSL、RGBA、HSLA)?
- java - 使用 Spring 为 2 个 DB 使用 2 个数据源
- entity-framework - EF6 OutOfMemoryException 使用 varbinary(max) 属性评估实体
- java - org.openqa.selenium.json.JsonOutput.write(Ljava/lang/Object;Ljava/lang/reflect/Type;) 由于 JsonException:尝试关闭不完整的 json 流
- jsp - 错误 JSP 中的复选框计数
- python - for 循环超过 2^n 个项目瓶颈
- c# - 更改 .NET Label 控件的高度以适合换行文本
- javascript - IE 中的 Object.assign 解决方法
- javascript - Vue.js 更新数组中的小计