When I use () when calling javascript function

So, in previous questions I was told to call / execute / run type functions thisFunc;instead thisFunc();.

And I found that sometimes it works, and sometimes not.

<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>

In this code (and please tell me if this is terrible), because I use setInterval to call the function with the parameter that I found during the study, it needs to be called as it was mentioned above.

So two questions

  • When should I really use () when calling functions?

  • , , 1. 1, , , , , .

!

+3
3

, . , . :

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 .

+4

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

(), ,

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,

Say that you have some functions that did the math, but you don't want to write a logging method for all of them.

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

or change a function to provide a function instead of a log function, and you can do anything with the answer

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

All Articles