简体   繁体   English

调用JavaScript函数的正确方法是什么?

[英]What's the correct way to call JavaScript Function?

In the following code, the function writeMessage is called without parenthesis. 在以下代码中,调用函数writeMessage不带括号。 However it works fine but Is it a correct way of function calling in javaScript or its better to use parenthesis along with writeMessage() . 但是它工作正常,但是在javaScript中调用函数是正确的方法还是更好的方法是将括号与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. 您将writeMessage函数分配为window对象的onload字段。 The actual call is performed (internally) as window.onload() which is equivalent to writeMessage() in your case. 实际的调用(在内部)作为window.onload() ,在您的情况下等效于writeMessage()

In the following code, the function writeMessage is called without parenthesis. 在以下代码中,调用函数writeMessage时不带括号。

Actually, it isn't. 其实不是。 The code 编码

window.onload = writeMessage;

does not call the function. 调用该函数。 It assigns the function to the onload property of window . 它将函数分配给windowonload属性。 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(); 您要做的就是调用writeMessage并将调用结果分配给window.onload ,就像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. 请注意,您实际引用的代码(在页面加载时执行document.write将清除刚刚加载的页面,并将其替换为文本“ Hello world”,因为在页面后调用document.write时加载完成,这意味着document.open ,这将清除页面。 (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). (试一试这里 ,源代码在这里 。)在现代网页和应用程序,你几乎从来不使用document.write ,但在你做的极少数情况下,它必须在运行的页面被加载代码(例如,不迟)。

the () is used to EXECUTE the function ()用于执行功能

when you write 当你写

window.onload = writeMessage; window.onload = writeMessage;

you actually set a delegate ( pointer to a function to be executed) for which - when the onload event will occour. 您实际上设置了一个委托pointer要执行的函数的pointer ),该委托将在onload事件发生时发生。

That's correct already. 没错

You don't need parenthesis because you're just storing the function in window.onload , not calling it yourself. 您不需要括号,因为您只是将函数存储在window.onload ,而不是自己调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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