JavaScript function expressions

Source: Internet
Author: User

1. There are two ways to define a function in JavaScript, one is a function declaration and the other is a function expression.

The function declaration method is as follows:

function functionname (arg0, arg1 ...) {  function Body  }

The first is the keyword function, and then the name of the function, which is the declaration of functions. A very important feature of the function declaration is that the function declaration is read before executing the code, which means that you can put the function declaration after the statement that called him. As follows:

1 test (); 2 function Test () {3   alert (' Hello world! ' );   4 }

This makes no mistake, because the function declaration was read before the code was executed.

The most common form of a function expression is as follows:

var function () {   function body  }

This function expression looks like a variable assignment statement, which creates an anonymous function and assigns it to functionname. One reason to create an anonymous function is that it doesn't have a name after the keyword function.

Since it is an expression, you must first assign a value before using it, and the following code will give an error:

test (); var function () {   alert ("Hello world!" );}

The biggest difference between function expressions and function declarations is the elevation of function declarations, which means that function declarations can be read into memory before they are executed. Look at the following code:

         if (condition) {             function  demo () {                 alert ("Hello");             }         } Else {             function  demo () {                 alert ("Ni hao!") );             }         }

On the surface, when condition is true, use the definition of a demo to use a different definition for fale, but in fact this is an invalid syntax, and even an error will be in the strict mode ' use strict '.

Because the function declaration has been read before execution, most browsers will overwrite the first function declaration with the second one. But if you use a function expression, there is no problem.

2. Recursion

The recursive function is formed in the case of the function call itself, the following code:

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

This is a classic recursive factorial function. Although it does not seem to be a problem, the following code executes the error.

var test=null; Test (4);

Because the function of factorial is called again in the recursive function, but the factorial is already null, the error will be made. So in this case it is recommended to use Arguments.callee, the following code

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

We know that in every function there is this variable, which represents the argument in each function, for example, arguments[0] means the first argument passed, Arguments[1] represents the second argument passed, and so on. Arguments Instead, Arguments.callee represents a pointer to a function that is currently executing, which points to the currently executing function, so he can implement a recursive function. But this syntax in strict mode ' use strict ', this method will error. However, there is a way, the function expression of the way to express recursion, strict mode will not error, as follows

var factorial = (function fn (num) {       if (num <= 1) {            return 1;       } else{           Return num * FN (num-1);       }});

3. Closures

What is a closure? Closures are functions that have access to variables in a function scope. A common way to create closures is to create a function inside a function and return it. As follows:

function createfactory (name) {        returnfunction(Object1, Object 2) {        var value1 = Object1[name];         var value2 = Object2[name];        return vale1- value2;   }}    

In the preceding code, an anonymous function is returned, and the variable name in the external function is accessed in the anonymous function. This anonymous function is returned, and the call can also be accessed to name in other places, without error, due to the scope chain containing the external function createfactory in the scope chain of the inner function. What is a scope chain? Every function has its own execution environment, when executing a function, the function will be placed in an environment stack, after execution, the stack will pop up, and give control to the previous function. When the code executes in an environment, it creates a scope chain for the variable object. The scope chain guarantees an orderly access to the variables of the current execution environment.

Continue tomorrow.

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.