[英]Differences between window.onload = function(){ .. } / window.onload = function(){ .. }();
I'm using in a project the following code which is not working: 我在项目中使用以下代码,该代码无效:
window.onload=function(){
//code here
};
but if I add at the end () it works: 但如果我在最后添加()它的工作原理:
window.onload=function(){
//code here
}();
My question is, what's the difference? 我的问题是,有什么区别? What does the () at the end? ()最后是什么?
I presume that the first one doesn't work because somewhere else the "onload" has been already called killing this one. 我认为第一个不起作用,因为其他地方的“onload”已被称为杀死这个。
Would it have the same behaviour if I always use the second option ? 如果我总是使用第二个选项,它会有相同的行为吗?
()
at the end of function, calls this function
immediately after declaration ()
在函数结束时,在声明后立即调用此function
window.onload=function(){
//code ehere
}() // function is called
And in this case 在这种情况下
window.onload=function(){
//code here
};
function will be called after 函数将被调用
window.onload()
When you have ()
after a lambda function such as that, it means you're calling the function immediately on that line. 当你在lambda函数之后有()
,它意味着你在那一行上立即调用函数。
So, for example, 所以,例如,
var x=function() {
return 5;
}();
console.log(x);
would log 5 in the console. 将在控制台中记录5。 In the case of 如果是
window.onload=function() {
//code here
}();
that function most likely returns another function that gets called when the page loads. 该函数最有可能返回页面加载时调用的另一个函数。
For example, 例如,
window.onload=function() {
return function() {
console.log("Hello!");
};
}();
will log "Hello!" 将记录“你好!” in the console when the page loads. 在页面加载时在控制台中。
function
is assigned to onload
function
被分配给onload
window.onload=function(){
//code ehere
};
result of function
is assigned to onload
function
结果被分配给onload
window.onload=function(){
//code ehere
}();
With the ()
the function you define is called immediately. 使用()
,您定义的函数会立即调用。 In that case, it better return a function to assign to window.onload. 在这种情况下,它最好返回一个函数来分配给window.onload。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.