Javascript return with colon

前端 未结 3 1024
谎友^
谎友^ 2020-12-13 02:01

I am learning JavaScript and have come across of the structure below:

var Test = (function () {

  function func1() {
      //do something.....
  }

  functi         


        
3条回答
  •  Happy的楠姐
    2020-12-13 02:27

    It's a literal object in the return statement. It's like creating an object and then returning it:

    var obj = {
        func1: func1,
        func2: func2,
        func3: func3
    };
    return obj;
    

    The literal object syntax creates an object and sets its properties, just like:

    var obj = new Object();
    obj.func1 = func1;
    obj.func2 = func2;
    obj.func3 = func3;
    return obj;
    

    The purpose of returning the object is to reveal the functions inside the function to the code outside, while creating a scope for private variables that the functions can use.

    When not using private variables, the code does the same thing as:

    var Test = {
      func1: function() {
          //do something.....
      },
      func2: function() {
          //do something.....
      },
      func3: function() {
          //do something.....
      }
    };
    

    Private variables are declared inside the function scope, and are only reachable by the functions inside it. Example:

    var Test = (function () {
    
      var name;
    
      function setName(str) {
        name = str;
      }
    
      function getName() {
        return name;
      }
    
      return {
          setName: setName,
          getName: getName
      };
    
    })();
    
    Test.setName("John Doe");
    var name = Test.getName();
    

提交回复
热议问题