JavaScript function declaration and function expression

Source: Internet
Author: User

When I read another blog today, I found thatArticleI have been talking about function declarations and function expressions,

I was a little dizzy, and I sorted it out later. In fact, these two concepts have been used before, but they are not noticed!

1.

Function declaration:

 
FunctionA () {alert ("Hello World")}//This is a function declaration.

Function expression:

 
VaRA =Function() {Alert ("Hello World")}//This is a function expression.

So what are the differences between them?

The parsing of the function declaration is in the pre-execution stage, that is, the browser is ready to executeCodeTimeAnd function expressions, just like defining other basic types of variables, will be parsed only when a certain sentence is executed..

2. The following are some weird functions.

 
~FunctionA () {alert (1111);}();
 
+FunctionA () {alert (1111);}();

However ~ + After removal, they will report a syntaxerror. This is because from the perspective of Syntax Parsing, JavaScript cannot directly use parentheses after function declaration, while function expressions do not have this restriction. By adding "~ "," + ","-","! "Operator, you can let the syntax parser regard it as a function expression, but the performance of different operators is not the same. If you want to know, refer to the following blog: http://www.swordair.com/blog/2011/10/714 /. In fact, the above functions can be written in this way.

 
VaRA =Function() {Alert (1111);}();

However, another problem occurs because you define a variable that will pollute the current running environment and bring potential risks.

However, if you do not like to add "~ "," + ","-","! "Operator, which can be written as follows. In fact, this is also a common method for many JS libraries.

(FunctionA () {alert (1111);})();

I believe that those who have read prototype, jquery, and other libraries must have seen this method.

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.