简体   繁体   中英

What is meaning of “()” in this code[closure]

$(document).ready(function(){
    var dash = function(){
            return{
             bindEvents: function(){
             }
            };      
    }();
window.methods = dash;
methods.bindEvents();
 });

The above code doesnot work without " () ". pls Explain why we need to use????

and also

         return{
         bindEvents: function(){
                               }
         };

is working fine. but if i align curly brace below the return statement. it throws an Error

          return
            {                  // throws an error
         bindEvents: function(){
                               }
             };

pls Explain.

Lets look at the points you have mentioned in your question:

$(document).ready(function(){
   var dash = function(){
        return{
           bindEvents: function(){}
        };      
   }();
   window.methods = dash;
   methods.bindEvents();
});

1 - The above code doesnot work without "()". pls Explain why we need to use????

Because this is a syntax of (IIFE--Immediately-Invoked Function Expression) which means it is an expression to execute itself as soon as document loads, think of jQuery library, which is developed same way.

return
      {   // throws an error
        bindEvents: function(){}
      };

2 - but if i align curly brace below the return statement. it throws an Error

Well yes the compiler will warn that there is a syntax error because if you move your curly brace down to the line then when you use browser to see your page or your function then what it does that, it automatically adds a ; there so it becomes return; .

so the output is something like:

return;
      {   // throws an error
        bindEvents: function(){}
      };

below it there is an object which is not getting returned back from it so it is causing issues.

It will immediately execute the function you defined there

function() {
 return{
  bindEvents: function(){}
  };      
}

Without it dash would point to a function you defined, with it dash will contain the result of funcion execution in this case object:

{
  bindEvents: function(){}
}

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