When To Use Parentheses With Javascript Function
Solution 1:
showText returns the function showText.
showText() runs the function showText and returns the result.
When you attach a function to an event handler like .onclick, it is expecting a function.
You can call a function and return the result to an event like this: document.getElementById("mybutton").onclick = showText(); provided the function itself returns a function:
function showText() {
return function () {
alert('hello world');
}
}
Solution 2:
In Javascript functions are first class citizens which means they can be assigned to a variable ... that is what you are doing i the first one ... You are basically setting the onclick to a function of your choice (telling the browser that when this is clicked ... call this function)
By using () you are calling the function ..
I can also do something like this
function test() {
alert('Alert something');
}
var a = test;
a();
Solution 3:
When you have a statement like:
onclick = showText;
the right hand side expression is evaluated and the result assigned to the left hand side. If the identifier showText resolves to a function object, a reference to that object is assigned.
If showText is followed by a formal parameter list enclosed in brackets, i.e. showText(), then the function is called with the supplied parameters and the result is assigned. The formal parameter list can be empty.
Post a Comment for "When To Use Parentheses With Javascript Function"