Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript syntax: function calls and using parenthesis

why does this work..

<script type="text/javascript">
<!-- 

function myAlert(){
    alert('magic!!!');
}


if(document.addEventListener){   
    myForm.addEventListener('submit',myAlert,false); 
}else{   
    myForm.attachEvent('onsubmit',myAlert); 
}
// -->
</script>

but not this ????

<script type="text/javascript">
<!-- 

function myAlert(){
    alert('magic!!!');
}


if(document.addEventListener){   
    myForm.addEventListener('submit',myAlert(),false); 
}else{   
    myForm.attachEvent('onsubmit',myAlert()); 
}
// -->
</script>

the difference being the use of parenthesis when calling the myAlert function.

the error I get..

"htmlfile: Type mismatch." when compiling via VS2008.

like image 382
madcolor Avatar asked Feb 27 '09 04:02

madcolor


People also ask

How do you use parentheses in JavaScript?

In JavaScript we only write a value in the parentheses if we need to process that value. Sometimes the purpose of the function is to perform a task rather then process some kind of input. Examples: var sayHello = function() { console.

What is Call () in JavaScript?

The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.

What is the difference between calling function with parentheses and without in JavaScript?

Using () after a function means to execute the function and return it's value. Using no () means to fetch the function to be passed along as a callback.


1 Answers

The () after a function means to execute the function itself and return it's value. Without it you simply have the function, which can be useful to pass around as a callback.

var f1 = function() { return 1; }; // 'f1' holds the function itself, not the value '1'
var f2 = function() { return 1; }(); // 'f2' holds the value '1' because we're executing it with the parenthesis after the function definition

var a = f1(); // we are now executing the function 'f1' which return value will be assigned to 'a'
var b = f2(); // we are executing 'f2' which is the value 1. We can only execute functions so this won't work
like image 78
Luca Matteis Avatar answered Nov 09 '22 11:11

Luca Matteis