Self-executing functions in JavaScript

Source: Internet
Author: User

Learning ES6 encountered the self-executing function, feel the need to write down, on the one hand to deepen their memories, on the other hand can also share to everyone.

What is a self-executing function?

The self-executing function is meant to be an anonymous function that does not pollute the global variable namespace, which is equivalent to creating a scope of its own, and here's how it works:

function foo () {...}     This is the definition, Declaration; the definition simply lets the interpreter know that it exists, but does not run. Foo ();                   This is the statement, Statement; The interpreter will run it when it encounters a statement.

The function above is a traditional function, it is a bit verbose, and it will pollute the global namespace, so it is not friendly to us, so the self-executing function appears, the following wording:

(function foo () {...}) ();
(function foo () {...} ());//recommended to use this form

The code block above is the self-executing function of two forms, it is recommended to use the following form, specifically, I do not know, perhaps because the package is more like encapsulating a function, you can understand. Traditional functions such as: function foo (...) {}, it is actually a declaration, for the interpreter, as if you had written a string "function foo (...) {} ", it needs to be executed using a parse function, such as Eval (). So put () directly behind the declaration is not executed, this is the wrong syntax. How do you get it right? It's easy to say, as long as you turn the declaration into an expression. This is the function in the code block above.

I hope you will understand, and I would be honored.

  


Self-executing functions in JavaScript

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.