简体   繁体   中英

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.

Would it have the same behaviour if I always use the second option ?

() at the end of function, calls this function immediately after declaration

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.

So, for example,

var x=function() {
    return 5;
}();
console.log(x);

would log 5 in the console. 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

window.onload=function(){
 //code ehere
};

result of function is assigned to 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.

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