window.onload = init(); 和有什么区别和 window.onload = init;
根据我收集的信息,前者将函数返回语句的实际值分配给 onload 属性,而后者分配实际函数,并将在窗口加载后运行。但我还是不确定。感谢任何可以详细说明的人。
From what I have gathered, the former assigns the actual value of whatever that functions return statement would be to the onload property, while the latter assigns the actual function, and will run after the window has loaded. But I am still not sure. Thanks for anyone that can elaborate.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将 onload 事件分配给执行 init 函数时返回的任何内容。
init
将立即执行(例如,现在,不是当窗口加载完成时执行)和结果将被分配给window.onload
。您不太可能想要这样,但以下内容是有效的:将 onload 事件分配给函数 init。当 onload 事件触发时,init 函数将被运行。
assigns the onload event to whatever is returned from the init function when it's executed.
init
will be executed immediately, (like, now, not when the window is done loading) and the result will be assigned towindow.onload
. It's unlikely you'd ever want this, but the following would be valid:assigns the onload event to the function init. When the onload event fires, the init function will be run.
将 foo 的值赋给 window 对象的 onload 属性。
将调用 foo() 返回的值赋给 window 对象的 onload 属性。该值是否来自 return 语句取决于 foo,但它返回一个函数(需要 return 语句)是有意义的。
当load事件发生时,如果window.onload的值是一个函数引用,那么window的事件处理程序将调用它。
assigns the value of foo to the onload property of the window object.
assigns the value returned by calling foo() to the onload property of the window object. Whether that value is from a return statement or not depends on foo, but it would make sense for it to return a function (which requires a return statement).
When the load event occurs, if the value of window.onload is a function reference, then window's event handler will call it.
好的答案,还需要补充一件事:
浏览器运行时忽略设置为 DOM 事件(例如 window.onload)的非对象(
字符串、数字、true、false、未定义、null、NaN
)值。因此,如果您编写window.onload
= 10 或任何上述值类型(包括混合string
),事件将保持null
。更有趣的是,事件处理程序将获取任何对象类型值,即使
window.onload = new Date
是一个非常有效的代码,当您记录window.onload 时,它会提示当前日期
。 :) 但当window.load
事件触发时,肯定不会发生任何事情。因此,请始终为 JavaScript 中的任何事件分配一个函数。
Good answers, one more thing to add:
Browser runtimes ignore non-object (
string, number, true, false, undefined, null, NaN
) values set to the DOM events such as window.onload. So if you writewindow.onload
= 10 or any of the above mentioned value-types (including the hybridstring
) the event will remainnull
.What is more funny that the event handlers will get any object type values, even
window.onload = new Date
is a pretty valid code that will prompt the current date when you log thewindow.onload
. :) But sure nothing will happen when thewindow.load
event fires.So, always assign a function to any event in JavaScript.