简体   繁体   中英

What's the correct way to call JavaScript Function?

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");
}

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.

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 (eg, not later).

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.

That's correct already.

You don't need parenthesis because you're just storing the function in window.onload , not calling it yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM