JavaScript function expressions

Source: Internet
Author: User
Tags bitwise variable scope

In ECMAScript, there are two most frequently used methods of creating function objects, that is, using function expressions or using function declarations. In this regard, the ECMAScript specification understood a little. That is, the function declaration must always have an identifier (Identifier), which is what we call the function name, and the function expression can be omitted.

The syntax for function declarations is this:

<script>function functionname () {function Body}</script>

Firstis functionkeyword, this keyword means I declare a function, or I will declare a function, tell the browser, and then the name of the function, we say the name of the function must see the name of righteousness, and then inside is our function body, Can also be understood as function expressions. A nonstandard name attribute is defined for the function in the major mainstream browsers. This property provides access to the name specified by the function, which is always the same as the identifier behind the functions;

function functionname () {}alert (functionname.name);

The function declaration resolution steps are as follows: 1. Creates a new function object, formalparameterlist the specified number of parameters, and Functionbody specifies the function body.  Takes the scope chain in the currently executing environment as its scope. 2. Create a property named identifier for the current variable object. The value is result (1).


Function declaring elevation

One important feature about functions is the function declaration promotion. It means that the function declaration is read before the substitution code is read. This means that a function declaration can be placed behind a call to its amount, for example;

alert (functionname.name); function functionname () {}
This example does not throw an error, because the function declaration is read first before the alert;

function expression

Another way to create a function is to use a function expression:

function Expression:(function expressions are classified as anonymous and named function expressions)function Identifier opt (formalparameterlist opt) {functionbody}//Here is the named function expressionthe parsing steps for the named function expression are as follows:1. Create a new object2. Add result (1) to the top of the scope chain3. Create a new Function object, formalparameterlist Specify the number of parameters, Functionbody specify the function body.

The scope chain in the execution environment that is currently executing is used as its scope. 4. Create a property named identifier for result (1) with a value of result (3), read only, not delete 5. Removes result (1) 6 from the scope chain . Returns result (3) Simply speaking. ECMAScript is a context-sensitive way of distinguishing between the two: if function foo () {} is part of an assignment expression. It is thought to be a function expression.

Assuming that function foo () {} is included in a function body, or in the topmost part of the program, it is parsed as a function declaration.

Obviously, in the case of omitting identifiers. "Expression" can only be an expression.

function foo () {}; Declared, because it is part of the program var bar = function foo () {}; An expression. Because it is part of the assignment expression (assignmentexpression), new function Bar () {}; expression, because it is part of the new Expression (newexpression) (function () {    
  Another scenario:
(function foo () {}) This is also an expression of functions, which are included in a pair of parentheses. In its context, () constitutes a grouping operator, while the grouping operator can only include an expression. A lot of other examples: function foo () {}; function declaration (Functions foo () {}); Function expression: Note that it is included in the grouping operator try {(var x = 5);//The grouping operator can only include expressions, cannot include statements (Var is statements here)} catch (Err) {//SyntaxError (because "var x = 5" is a language Sentence, not an expression-the evaluation of an expression must return a value, but a statement evaluation may not return a value. --translation}
   The following is a brief talk about the similarities and differences between function declarations and function expressions.

There are very subtle and important differences in the behavior of declarations and expressions.

First, the function declaration is parsed and evaluated before whatever expression is parsed and evaluated.

Even if the declaration is in the last line in the source code, it is evaluated first in the expression that precedes the same scope. Simple Summary, where is the difference? 1. Declarations are always parsed at the beginning of the scope, and 2. Expressions are evaluated when they are encountered. Another important feature of function declarations is that the behavior of controlling function declarations through conditional statements is not standardized. Therefore, different circumstances may result in different results. That is: //Don't do it! //different browsers will have different return results.

if (true) {function foo () {return ' first ';}} else {function foo () {return ' second ';}} Foo ();
Remember. In this case, you use the function expression:
var foo;if (true) {foo = function () {return ' first ';};} else {foo = function () {return ' second ';};} Foo ();
 so. What exactly is the actual rule used to declare a function? Functiondeclaration (function declaration) can only be present in the program or functionbody (function body).

They cannot be present in block (blocks) ({...}). In For example, cannot be present in an if, while, or for statement. Because block (block) can only include statement (statements), and cannot include functiondeclaration (function declaration) such sourceelement (source element). There is one more aspect. A careful look at the resulting rules will also find that the only way to get expression to appear in block is now. is to make it part of the expressionstatement (expression statement). But. The specification explicitly stipulates that expressionstatement (expression statements) cannot begin with keywordfunction.

And this is actually saying. Functionexpression (function expressions) cannot be the same as in today's statement (statements) or blocks (don't forget that block is made up of statement). Because of the above limitation, just to function out of the current block (as in the example above), you should actually think of it as a syntax error rather than as a function declaration or an expression. So when should we use a function declaration or function expression? Function declarations can only be found in the "program code" today. means that they can only be in other function bodies or in global space, and their definitions cannot be assigned to a variable or attribute. Or it is passed as a parameter in the function call; The following sample is the consent usage of the function declaration, Foo (), bar (), and local () are declared through the function declaration pattern: //Global Environment

function foo () {}   function local () {  //Local Environment      function bar () {}          return bar;  }
When you cannot use a function declaration in syntax. You will be able to use function expressions. For example, pass a function as a parameter or define a function in the object literal ://This is an anonymous function expression
CallMe (function () () {   //pass a functions as the number of references});

//This is a named function expressioncallMe (function Me () {//Pass a function as a parameter, the function name is me}); // other function expressions
var MyObject = {      say:function () {   //I am a function expression  }  
This looks like a regular variable assignment statement, which is to create a function and copy it to the variable functionname. The function created in this case is called an anonymous function.

Because there is no identifier behind Functionkeyword.

The Name property of the anonymous function is an empty string. function expressions, like other expressions, must be copied before they can be used.

And the function expression does not function, promote, that is, run the function expression first, and then declare the error.

JavaScript has a lot of interesting ways to use it, and it can be found in Google Code search. For example:

<script>~function () {    alert ("Hello, World");} ();</script>
Try to know that the meaning of this code is to declare a function, and then immediately execute, because the variable scope in JavaScript is based on function, so this can avoid the variable pollution, but here the bitwise operator "~" At first glance let a person can't touch the mind, If you remove it and then execute it, you will get an error: SyntaxError.

Why do I get rid of the bitwise operator "~" Error after execution. This is due to the perspective of parsing from a grammatical point of view. JavaScript differs in that it is intended to use parentheses directly after a function declaration. The function expression does not have this limitation. By adding a "~" operator to the function declaration. It is possible for the parser to think of the back as a function expression, the same. Precede the function declaration with "!. +,-"operators are also feasible.

So why don't we use the following function expressions as follows?

<script>var foo = function () {    alert ("Hello, World");} ();</script>

Although there is no problem from the point of view of parsing, the code above is flawed, and it introduces a variable that may contaminate the existing execution environment. Pose a potential problem.

The method of using the bitwise operator "~" seems a bit artifice, in fact the function declaration is more readable with parentheses:

<script> (function () {    alert ("Hello, World");}) ();</script>

JavaScript function expressions

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.