JavaScript anonymous function and self-execution __ function

Source: Internet
Author: User

Example:

<script>
var a = 1;
var b = 2;
(function () {
	var b = 3;
	A + b;
}) ();
alert (a); 4
alert (b);//2
</script>

Indicates that the anonymous function has been executed--> this is the self execution of the anonymous function


Self-executed anonymous function

1. What is a self executing anonymous function?
It refers to a function such as this: (function {//code});

2. Why (function {//code}); can be executed, and function {//code} ();

(1). First, be clear about the difference between the two:
(function {//code}) is an expression, function {//code} is a declaration of functions.

(2). Second, JS "precompiled" features:
JS in the "precompiled" phase, will interpret the function declaration, but will be a slight.

(3). When JS executes to function () {//code} (), because function () {//code} has been interpreted in the precompiled phase, JS skips function () {//code} to attempt to execute ();
When JS executes to (function {//code}), because (function {//code}) is an expression, JS will be able to solve it to get the return value, because the return value is a function, and therefore encountered (), it will be executed.

In addition, the method of converting a function to an expression does not necessarily depend on the grouping operator (), we can also use the void operator, the ~ operator ...


Reference: http://www.jcodecraeer.com/a/jquery_js_ajaxjishu/2012/0628/290.html

http://bonsaiden.github.io/JavaScript-Garden/zh/#function. This

http://mianshiti.diandian.com/post/2013-04-05/40048538140

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.