function expressions in JavaScript

Source: Internet
Author: User

In JavaScript, functions are a very important object, and functions typically have three representations: function declarations, function expressions, and functions created by function constructors.

This article mainly looks at the function expression and its related knowledge points.

function expression

First, look at the representation of the function expression, which has the following four features (function expression, FE):

    • Where the expression must appear in the code
    • There is an optional function name
    • Does not affect variable object (VO)
    • Creating in the Code execution phase

Here are some examples of the four features of the function expression.

Fe feature Analysis

Example One : in the following code, "Add" is a function object, "Sub" is a normal JavaScript variable, but is assigned a function expression "function (A, b) { return A-B; } ":

function Add (A, b) {    return a + b;} var function (A, b) {    return A- b;} Console.log (Add (1, 3)); // 4Console.log (sub (5, 1)); // 4

In this example, you can visually see the first two features of a function expression:

    • Where the expression must appear in the code
      • " function (A, b) { return A-A;} " The expression position that appears in the JavaScript statement
    • There is an optional function name
      • " function (A, b) { return A-A;} " This function expression has no function name and is an anonymous function expression

example Two : to explain the other two features of the function expression, continue to look at the following example.

Console.log (Add (1, 3)); // 4 Console.log (sub); // undefinedconsole.log (sub (5, 1)); // uncaught typeerror:sub is not a function (...) function Add (A, b) {    return a + b;} var function (A, b) {    return A- b;}

In this example, the execution order of the code is adjusted, and this time the function "add" executes normally, but the execution of the function expression fails.

For this example, you can refer to the "JavaScript execution context" article, when the code starts to execute, you can get the global VO as shown.

In global Vo, the "add" function behaves as a "hoisting" effect of JavaScript, so it can be used even before the "add" definition;

However, for the "sub" variable, the "sub" is initialized to "undefined" according to the "execution Context" initialization process, and only executes to " var sub = function " (A, b) { return A-A;} "Sub" in VO will be assigned when the statement is called.

From the above example, you can see the fourth feature of the function expression

    • Creating in the Code execution phase

example three : further changes to the above example, this time adding a name to the function expression "_sub", that is, the use of a named function expression .

 var  sub = function   _sub (A, b) {Console.log ( typeof   _sub);  return  a- b;} Console.log (Sub ( 5, 1 //  function  //  console.log (typeof   _sub)  //  undefined  Console.log ( _sub (5, 1 //  Uncaught Referenceerror: _sub is not defined (...)  

According to the running result of this code, you can see the function name "_sub", only used inside the function of "_sub", when accessing "_sub" outside the function, we get "uncaught Referenceerror: _sub is not defined (...) ) "Error.

So through this you can see the third feature of the function expression:

    • Does not affect variable object (VO)

function Name of FE

Here, there must be a problem, "_sub" is not in Vo, where is it?

In fact, for a named function expression, the JavaScript interpreter does something extra:

    1. When the interpreter encounters a named function expression during the code execution phase, the interpreter creates a specific helper object before the function expression is created and adds it to the front end of the current scope chain
    2. Then when the interpreter creates the function expression, during the creation phase, the function acquires the [scope] property (the scope chain of the current function context)
    3. Thereafter, the function name of the function expression is added to the specific object as a unique property; The value of this property is referenced to the function expression
    4. The final step is to remove that particular object from the parent scope chain.

The following is a pseudo-code that represents this process:

Specialobject == specialobject +new=//Delete  //  Remove special objects from the scope chain Specialobject
function recursion

This section may be a bit of a dead-over, but here you want to demonstrate the possible problems with recursive calls and perform recursion in a more secure way by naming function expressions.

Here is an example of factorial, because the function object can also be changed, so the following situation may cause errors.

 function   factorial (num) { if  (num <= 1) { return  1;  else   { return  num * factorial (num-1 5 //  newfunc = factorialfactorial  = null  console.log (Newfunc ( 5 //  Uncaught typeerror:factorial is not a function (...)  

At this point, you can use the callee property of the arguments object of the function to solve the above problem, that is, in the function, always use "Arguments.callee" to recursively call the function.

function factorial (num) {    if (num <= 1) {        return 1;     Else {        return num * Arguments.callee (num-1);    }}

But the use of the above also has some problems, when in strict mode, "Arguments.callee" will not work properly.

A better solution would be to use a named function expression, so that no matter how "factorial" changes, it will not affect the function expression "function f (num) {...} " "

var factorial = (function  f (num) {    if (num <= 1) {        return 1;     Else {        return num * F (num-1);    }});
Modularity of code

In JavaScript, there are no block scopes, only function scopes, external variables and functions can be accessed inside the function, but variables and functions inside the function are inaccessible outside the function.

So, with functions (usually directly using function expressions), you can modularize JavaScript code.

Create a module

In order to be able to achieve the following purposes, we can create modules through function expressions.

    • Create a code module that can be reused
    • The module encapsulates content that the consumer does not care about, exposing only the interfaces provided to the user
    • Isolate from global namespace as much as possible to reduce contamination of global namespace

Let's look at a simple example:

varCalc = (function(){    var_a, _b; return{add:function(){            return_a +_b; }, Sub:function(){            return_a-_b; }, set:function(A, b) {_a=A; _b=b; }    }}()); Calc.set (10, 4); Console.log (Calc.add ());// -Console.log (Calc.sub ());//6

The code creates a "Calc" module with an anonymous function expression, which is a common way to create a module:

    • Create an anonymous function expression that contains the private variables and functions of the module itself;
    • By executing this function expression you can get an object that contains the public interface that the module wants to expose to the user.

In addition to returning an object, some modules use an object that contains the public interface of the module as a property of the global variable, in a different way.

This allows the module to be used directly from this property of the global variable, elsewhere in the code.

For example, the following example:

(function(){    var_a, _b; varRoot = This; var_ ={add:function(){            return_a +_b; }, Sub:function(){            return_a-_b; }, set:function(A, b) {_a=A; _b=b; }} root._= _; }.call ( This)); _.set (10, 4); Console.log (_.add ());// -Console.log (_.sub ());//6
function expressions that are called immediately

In the above two examples, anonymous function expressions are used, and are executed immediately. If you look at JavaScript code for some open source libraries, such as jquery, underscore, and so on, you will find similar anonymous function code that executes immediately.

A function expression that is called immediately is usually shown in the following form:

(function () {     /*Code*/ })();(function () {     /*Code*/ } ()); In underscore this JavaScript library, use the following method: (function () {     //establish the root object, ' window ' in the browser, or ' exports ' on the server.varRoot = This;/*Code*/}. Call ( This));

Here, the underscore module caches the global variable this directly and facilitates internal use of the module.

Summarize

This article briefly introduces the function expression in JavaScript, and explains the four features of the function expression through three examples.

    • Where the expression must appear in the code
    • There is an optional function name
    • Does not affect variable object (VO)
    • Creating in the Code execution phase

With the function expression, it is convenient to build the JavaScript module, through the module can achieve the following effect:

    • Create a code module that can be reused
    • The module encapsulates content that the consumer does not care about, exposing only the interfaces provided to the user
    • Isolate from global namespace as much as possible to reduce contamination of global namespace

function expressions in JavaScript

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.