(function () {}) (), a correlation study of function () {} ()

Source: Internet
Author: User

(function () {}) () is called self-executing anonymous function, you can use it to create a namespace, as long as you write all your own code in this special function wrapper, then the external cannot access, unless you allow.

Note that without the outer brackets, the function () {} () functions are not self-executing, an anonymous function, but not assigned to a variable

Look at the following example:

var text = (function() {                  alert ("1");                       var a = "AA";                          }) ();          Console.log (a);    

This is a self-executing function, the alert executes, internal parameters cannot be called outside

function () {                  alert ("1");                       var a = "AA";                          } ();          Console.log (a);    

This function cannot be executed, will error, anonymous function cannot execute

But after the assignment, you can do it:

        var function () {                  alert ("1");                       var a = "AA";                          } ();          Console.log ();            

The function can execute equivalent to Var text=function () {};text ();

In addition, if the self-executing function is assigned to a variable, the result is the same as above, the value of the variable is the return value of the self-executing function, here you can take an example of the previous essay:

varText = (function(){                  varA =NULL; varb =function(){                      returnA;                  }; varpublic =function(value) {//Privileged Methods                  }; Public.prototype.setName=function(value) {a=value; return  This;                  }; Public.prototype.getName=function(){                      returnA;                  }; returnPublic//return to privileged methods          })(); Console.log (text)

The value of the text here is:

(function () {}) (), a correlation study of function () {} ()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.