调用 JavaScript 函数的正确方法是什么?
在以下代码中,调用函数 writeMessage
时不使用括号。然而它工作得很好,但是这是在 javaScript 中调用函数的正确方法还是最好将括号与 writeMessage()
一起使用。
window.onload = writeMessage;
function writeMessage()
{
document.write("Hello World");
}
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");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
window.onload = writeMessage;
不是一个调用 - 它是一个赋值。您将writeMessage
函数指定为window
对象的onload
字段。实际调用(在内部)作为window.onload()
执行,在您的情况下相当于writeMessage()
。window.onload = writeMessage;
is not a call - it's an assignment. You assign thewriteMessage
function as theonload
field of thewindow
object. The actual call is performed (internally) aswindow.onload()
which is equivalent towriteMessage()
in your case.事实上,事实并非如此。该代码
不调用该函数。它将函数分配给
window
的onload
属性。在浏览器中加载页面的过程的一部分是在加载过程完成后触发分配给该属性(如果有)的函数。如果您编写的
内容是调用
writeMessage
并将调用的结果分配给window.onload
,就像x = foo();
。请注意,您实际引用的代码(在页面加载时执行
document.write
)将清除刚刚加载的页面并将其替换为文本“Hello world”,因为当您页面加载完成后调用document.write
,它意味着document.open
,这会清除页面。 (这里试试;源代码此处。)在现代网页和应用程序中,您几乎从不使用document.write
,但在极少数情况下,它必须在运行的代码中当页面正在加载时(例如,不稍后)。Actually, it isn't. The code
does not call the function. It assigns the function to the
onload
property ofwindow
. 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
what you'd be doing is calling
writeMessage
and assigning the result of the call towindow.onload
, just likex = 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 calldocument.write
after the page load is complete, it impliesdocument.open
, which clears the page. (Try it here; source code here.) In modern web pages and apps, you almost never usedocument.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).()
用于在编写
window.onload = writeMessage;
时执行函数。您实际上设置了一个委托(指向要执行的函数的
指针
) - 当onload
事件发生时。the
()
is used to EXECUTE the functionwhen you write
window.onload = writeMessage;
you actually set a delegate (
pointer
to a function to be executed) for which - when theonload
event will occour.这已经是正确的了。
您不需要括号,因为您只是将函数存储在
window.onload
中,而不是自己调用它。That's correct already.
You don't need parenthesis because you're just storing the function in
window.onload
, not calling it yourself.