The function expression of "JavaScript"

Source: Internet
Author: User
Tags closure

Today, the main review of the "JavaScript Advanced program" function expression in this chapter, mainly their own closure and this concept or not clear, resulting in a small demo when this piece of the completion of ignorance, first do a knowledge comb, and then continue to strengthen practice it.

characteristics of function Expressions
function declaration, which reads the function declaration before executing the code (meaning that the function declaration can be placed after the statement that called it)
function functionname (arg0,arg1,arg2) {             // function Body }

When you use a function expression to define a function, you do not need to name the function, or you can create an anonymous function.

Features of function expressions:
    • function expressions are different from function declarations. Function declarations require a name, a function expression is not required, and a function expression without a name is also called an anonymous function.
    • Recursive functions should always use Argument.callee to recursively invoke themselves, instead of using function names-the function names may change.
function factorial (num) {   if(num<=1) {      return 1;} Else {     return Num*arguments.callee (num-1);     }}
Second, closed package

closure: refers to a function that has access to a variable in another function scope.

functioncreatecomparisonfunction (PropertyName) {return function(object1,object2) { var value1 = Object1[propertyname];  var value2 = Object2[propertyname]; Intrinsic functions if(value1<value2) {                         return-1; }Else if(value1>value2) {                       return1                  }Else{                       return0; }}//The intrinsic function accesses the variables in the external function PropertyName   

How to thoroughly understand closures?

Know the details about how to create a scope and what the scope chain does.

Variable object: each execution environment in the background has an object that represents a variable.

The variable object for the global environment always exists, and the object variable of a local environment such as the Compare () function exists only during the execution of the function.

function Compare (value1,value2) {   //① defines the Compare function     if(value1<value2) {          Return -1;} Else if (value1>value2) {        return 1;} Else {       return 0;    }} var result = Compare (5,10);  ② called compare () in the global scope, a live object containing arguments, value1, value2 is created

The variable object (result, compare) of the global execution environment is second in the scope chain of the Compare () execution environment.

In general, when the function is finished, the local active object is destroyed and only the global scope (global variable object) is stored in memory.

      1. In a background execution environment, the scope chain of a closure contains its own scope, the scope of the containing function, and the global scope.
      2. Typically, the scope of a function and all of its variables are destroyed after the function executes.
      3. However, when a function returns a closure, the scope of the function is persisted in memory until the closure does not exist.
about this object

The This object is bound by the run-time function-based execution environment, in the global function , this equals window, and when the function is invoked as an object , this equals that object

(each function automatically gets two special variables when called, this and arguments, when the intrinsic function searches for both variables, it only searches for its active object, so it is always possible to access these two variables in the outer function directly.) )

However, the this object in the outer scope is stored in a variable that can be accessed by a closure, allowing the closure to be accessed by the enclosing packet.

 var  name = "The window" ;  var  object = {name:  "My object"  function   () { var  that = this;  return  function   () { return   THAT.N            Ame      };   }};alert (Object.getnamefunc ());  //  "My Object"  

When the scope of a closure holds an element that cannot be destroyed, its memory is never recycled, which results in a memory leak. So we use closures to mimic block-level scopes to solve problems.

Iii. impersonation of block-level scopes
    1. Create and call a function immediately so that you can execute the code in it without saving a reference to the function in memory.
    2. The result is that all variables inside the function are understood to be destroyed, without causing a memory leak or a variable pollution global scope
function Outputnumbers (count) {   (function() {           for (var i =0;i<count; i++) {               alert (i);  The //anonymous function is a closure that can access all variables in the containing scope      }) ();      alert (i);}
Iv. Private variables

Variables defined in any function can be considered as private variables because they cannot be accessed outside the function.

Private variables include the parameters of the function, local variables, and other functions defined inside the function.

    • We can use closures to implement common methods that have access to private variables, which are also called privileged methods
    • Instead of implementing the privileged method, we use the constructor pattern, the prototype schema, or the module pattern, the enhanced module pattern, to implement the privileged method of the instance.

Prototype mode

(function  MyObject () {      // private variable and private function      var privatevariable = 10 ;             function privatefunction () {            returnfalse;}       //Constructors

MyObject = function () { ///Functions declaration can only create local functions, so use function expressions
};
      Public/Privileged Methods
      function () {   

++return privatefcuntion ();
};
})();

In this pattern, private variables and functions are shared by the instance, because the privileged method is defined on the prototype, because all instances use the same function.

A privileged method, as a closure, always holds a reference to a containing scope.

(function(){            varName= ""; person=function(value) {Name=value;    }; Person.prototype.getName=function(){           returnname; } Person.prototype.setName=function(value) {Name=value;}; })();varPerson1 =NewPerson ("Nicholas"); alert (Person1.getname ()); //"Nicholas"Person1.setname ("Greg"); alert (Person1.getname ()); //"Greg"varPerson2 =NewPerson ("Michael"); alert (Person1.getname ()); //"Michael"Alert (Person2.getname ());//"Michael"

Creating static private variables in this way increases the reuse of code by using prototypes, but each instance does not have its own private variables.

Module mode

Create private variables and privileged methods for a singleton, which refers to an object that has only one instance.

In a Web application, we often need to use an instance to manage application-level information, and this simple example creates a application object for managing the component.

varApplication =function(){ //private variables and functions varcomponents =NewArray (); //Declare a private components array first //InitializeCompenents.push (Newbasecompenent ()); //And adds a new instance of Basecomponent to the array //Public return{ //returns the Getcomponentcount () and RegisterComponent () methods of the object, both of which are privileged methods that have access to the array component Getcompenentcount: function(){ returncompenents.length; }, RegisterComponent:function(component) {if(typeofComponent = = "Object") {Components.push (component); } } };} ();

In short, you can use module mode if you have to create an object and initialize it with some data, and also expose a way to access the private data.

The function expression of "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.