What is the use of return statement inside a function?

后端 未结 3 1336
北荒
北荒 2020-12-18 09:06
    var obj = {

        func: function() {    
        return: {
           add: function() {
             }
          } 
        },
        somefunc: function() {
         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-18 09:55

    An anonymous function that is executed immediately is commonly used to create a scope. Any variables that you declare inside the scope is local to the function, so they don't pollute the global scope.

    The return statement is used to return an object from the anonymous function:

    var hash = (function() {
      return { ... };
    })();
    

    You could write the same using a named function:

    function createHashObject() {
      return { ... };
    }
    
    var hash = createHashObject();
    

提交回复
热议问题