Cliché javascript function expression _javascript tips

Source: Internet
Author: User

There are two main methods of creating functions in javascript: function declarations and function expressions. Both of these methods have different scenarios. The main focus of this note is on several features of the function expression and its usage scenarios, which are described in one by one below.

Main Features

• Optional Function name

A function name is a necessary part of a function declaration, the function name is equivalent to a variable, the new defined function will be copied to the variable, and later the function call will need to go through this variable. For a function expression, the name of the function is optional, such as the following example:

var sub = function (A1,A2) {return 
  a1-a2; 
} 

In this example, the function expression has no name and belongs to an anonymous function expression. Look at the following example:

var sub = function f (a1,a2) {return 
  a1-a2; 
} 
Console.log (f (5,3));  Error Invocation Method 
Console.log (sub (5,3));  Calling the right way 

In this example, the name of the function expression is F, and the name F actually becomes a local variable within the function and refers to the function object itself, which is useful when the function is recursive, which is described in detail later.

• Create in execution phase (different from function declaration)

This feature is where function expressions differ significantly from function declarations.

The interpreter does not discriminate between the two ways when parsing JavaScript code. The interpreter first reads the function declaration and makes it available before executing any code, and for a function expression, it must wait until the interpreter executes to the line of code it is in before it is truly parsed. For example:

Console.log (Add (1,2));  "3" 
Console.log (sub (5,3));  "Unexpected identifier", error 
function Add (A1,A2) {return 
  a1+a2; 
} 
var sub = function (A1,A2) {return 
  a1-a2; 
} 

The first statement can be performed correctly. When the code is evaluated, the JavaScript engine declares the function on the first pass and places it at the top of the source tree with a procedure called function declaration elevation. That is, the function declaration is "hosting" in the creation phase of the execution environment (when the function is invoked but has not started executing). So, even if the code that declares the function is behind the code that calls it, the JavaScript engine also promotes the function declaration to the top. However, if you change the function declaration to a function expression, an error is made during execution. The reason is that a reference to a function is not included in the variable sub until the statement where the function is executed. That is, the variable sub is only assigned at the code execution stage. In addition to the differences above, the syntax of function declarations and function expressions is equivalent in other respects.

• Does not affect variable objects

var sub = function f (a1,a2) { 
  console.log (typeof f);//"function" return 
  a1-a2; 
} 
Console.log (typeof f);  "Uncaught referenceerror:f is not defined (...)" 

As you can see from the example above, the function name F can only be used inside the function object, and the function name of the function expression does not exist in the variable object.

Working with scenes

function expressions use a lot of scenes. The following describes the application of function recursion and code modularity.

• function recursion

Look at the following example:

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

This is a classic factorial function, but one of the problems with this example is that the function name factorial is tightly coupled to the function body, and the following statement is an error:

var anotherfactorial = factorial; 
factorial = null; 
Console.log (Anotherfactorial (5));  "Uncaught typeerror:factorial is not a function" 

The reason for the error is that the factorial function is called inside the function body, and the variable factorial reference to the function has been lifted so that the error is not correct. The workaround for this situation can generally be solved by using Arguments.callee, Arguments.callee always points to the current function, for example:

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

This performs the anotherfactorial function here to get the correct result. However, under the strict mode "strict", Arguments.callee is not accessible through scripting, so you can use a function expression to solve this problem, for example:

var factorial = (function f (num) { 
  if (num <= 1) {return 
     1; 
  } else{return 
     num * f (num-1); 
  } 
); 
Console.log (factorial (5));  "120" 

• Code modularity

There is no block-level scope in JavaScript, but we can use function expressions to modularize JavaScript code. The modular code can encapsulate details that are not required to be known to the user, exposing only the user-related interfaces while avoiding contamination of the global environment, such as:

var person = (function () { 
  var _name = ""; 
  return{ 
    getname:function () {return 
       _name; 
    }, 
    setname:function (newname) { 
       _name = newname; 
    } 
  }; 
} ()); 
Person.setname ("John"); 
Person.getname ();  "John"

This example creates an anonymous function expression that contains the private variables and functions of the module itself; the execution result of this function expression returns an object that contains the public interface that the module exposes to the consumer. There are a number of specific forms of code modularity, such as an immediate execution function that is typically used in some common JavaScript libraries, similar to the following example:

(function () { 
  var _name = ""; 
  var root = this; 
  var person = { 
    getname:function () {return 
      _name; 
    }, 
    setname:function (newname) { 
      _name = newname;< c9/>} 
  }; 
  Root.person = person; 
Call (this)); 
Person.setname ("John"); 
Person.getname ();  "John"

This method directly uses the object that contains the module's public interface as a property of the global object, so that the module can be used directly elsewhere using this property of the global object.

The above cliché JavaScript function expression is small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.

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.