调用 JavaScript 函数时何时使用 ()

When do I use () when calling a javascript function

本文关键字:何时使 JavaScript 函数 调用      更新时间:2023-09-26

所以在之前的问题中,我被告知调用/执行/启动像thisFunc;这样的函数而不是thisFunc();

我发现有时有效,有时无效。

<script type='text/javascript'>
var valgo = 0;
var thing = "";
var lastPost = document.getElementById(<? echo $_SESSION['countything']; ?>); 
lastPost.style.opacity = valgo;
function valgogoer(thing){
valgo += .05;
if (lastPost.style.opacity < 1){
lastPost.style.opacity = valgo;
}
}

setInterval(function(){valgogoer(<? echo $_SESSION['countything']; ?>)}, 50);
// Somethings are leftover from when I was messing with it, like the parameter thing.
</script>

在这个代码中(请告诉我它是否很糟糕(,因为我使用 setInterval 来调用带有参数的函数,我通过研究发现它必须按照上面的方式调用。

所以两个问题

  1. 我什么时候应该在调用函数时使用 ((?

  2. 在上面的代码中,我怎样才能让它在不透明度达到 1 后停止执行该函数。目前它被限制为 1,但它仍在被调用,我有一种感觉,停止调用函数比调用它但不做任何事情更好。

谢谢!

当您想要调用函数时,可以使用括号。但如果只是想传递函数的内容,你不要。例子:

var a = function(){
    return "I'm a function";
}
var b = a;//Equals to function(){return "I'm a function";}
var c = a();//Equals to "I'm a function"

在事件处理程序中,不使用括号,因为您必须对浏览器说才能执行函数的内容。如果放了它们,浏览器会调用函数的返回值,可能会导致错误:

var a = function(){
    alert("Welcome to my site");
}
window.onload = a();//Wrong, equals to undefined, since the a function doesn't return any value
window.onload = a;//Correct, calls the function a when the event is fired

当您使用函数作为参数调用 setInterval 方法时,也会发生同样的事情。这就是为什么括号如此重要

当您

想要调用函数时,可以使用thisFunc()。当您希望将函数的引用作为值时,可以使用thisFunc

当函数没有参数时,可以使用引用进行回调:

function thisFunc() {
  // do something
}
window.setTimeout(thisFunc, 1000);

当你的函数有一个参数时,你需要把它包装在另一个函数中,以使用参数值调用它:

function thisFunc(param1) {
  // do something
}
window.setTimeout(function(){ thisFunc(42); }, 1000);

当然,您也可以将无参数函数包装在函数中:

function thisFunc() {
  // do something
}
window.setTimeout(function(){ thisFunc(); }, 1000);

您不需要使用匿名函数来包装函数,您可以使用命名函数并获取对该函数的引用:

function thisFunc(param1) {
  // do something
}
function callFunc() {
  thisFunc(42);
}
window.setTimeout(callFunc, 1000);

当您希望另一个函数执行您的函数时,可以使用()

function log(arg) { console.log(arg); }
setTimeout(log, 1000) // Logs undefined after 1 second

log("hi"); // logs the String hi

该功能是可重用的,因此您可以自己实际使用它

function logUsingTheLogMethod( callback ) {
    if ( typeof callback === "function" ) {
        callback( "This will log to the console!" );
        callback( log === callback ); // Logs true
    }
}
logUsingTheLogMethod( log );

这是 JS 中的常见模式,在方法中使用函数作为回调

假设您有一些执行数学运算的函数,但您不想为所有函数编写日志记录方法。

function add(a,b,fn) {
    if ( fn === log ) {
       fn( a + b );
    }
}
function subtract(a,b,fn) {
    if ( fn === log ) {
       fn( a - b );
    }
}
add(1, 2, log); // logs 3
subtract(5, 4, log) // logs 1

或者修改函数,以确保它是一个函数而不是日志函数,你可以对响应做任何事情

function add(a,b,fn) {
    if ( typeof fn === "function" ) {
       fn( a + b );
    }
}
// answer is automatically passed in by the calling add method
add( a, b, function ( answer ) { 
     // do ssomething with the answer
     alert( answer );
});