Reputation: 2679
In the following code, the function writeMessage
is called without parenthesis. However it works fine but Is it a correct way of function calling in javaScript or its better to use parenthesis along with writeMessage()
.
window.onload = writeMessage;
function writeMessage()
{
document.write("Hello World");
}
Upvotes: 0
Views: 335
Reputation: 148634
the ()
is used to EXECUTE the function
when you write
window.onload = writeMessage;
you actually set a delegate ( pointer
to a function to be executed) for which - when the onload
event will occour.
Upvotes: 1
Reputation: 1075029
In the following code, the function writeMessage is called without parenthesis.
Actually, it isn't. The code
window.onload = writeMessage;
does not call the function. It assigns the function to the onload
property of window
. Part of the process of loading the page in browsers is to fire the function assigned to that property (if any) once the loading process is complete.
If you wrote
window.onload = writeMessage();
what you'd be doing is calling writeMessage
and assigning the result of the call to window.onload
, just like x = foo();
.
Note that the code you've actually quoted, which executes a document.write
when the page loads, will wipe out the page that just loaded and replace it with the text "Hello world", because when you call document.write
after the page load is complete, it implies document.open
, which clears the page. (Try it here; source code here.) In modern web pages and apps, you almost never use document.write
, but in the rare cases where you do, it must be in code that runs as the page is being loaded (e.g., not later).
Upvotes: 2
Reputation: 32296
window.onload = writeMessage;
is not a call - it's an assignment. You assign the writeMessage
function as the onload
field of the window
object. The actual call is performed (internally) as window.onload()
which is equivalent to writeMessage()
in your case.
Upvotes: 5
Reputation: 16718
That's correct already.
You don't need parenthesis because you're just storing the function in window.onload
, not calling it yourself.
Upvotes: 0