我何时在调用javascript函数时使用()

时间:2012-05-19 00:00:14

标签: javascript function parameters

因此,在之前的问题中,我被告知要调用/执行/启动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,但它仍然被调用,我感觉它更好停止被调用的函数,而不是被调用但没有做任何事情。

  3. 谢谢!

3 个答案:

答案 0 :(得分:4)

如果要调用该功能,请使用括号。但如果只是想传递函数的内容,你就不会。例子:

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方法时,会发生同样的情况。这就是括号如此重要的原因

答案 1 :(得分:2)

如果要调用该函数,请使用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);

答案 2 :(得分:0)

如果希望其他功能执行您的功能,请使用()

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 );
});
相关问题