function expressions and closures

Source: Internet
Author: User

Briefly:

recently learned JavaScript function expressions and closures this piece, record their own study notes!

Learning ECMAScript, function expressions and ' object-oriented ' two blocks are difficult and important.

Reference books: <javascript Advanced Programming > Tools: EditPlus browser IE11, Chrome

There are two main ways to define a function in 1 javascript:

(1) Function declaration

function P () {//code}

(2) Function expression: Also called anonymous function

var p=function () {};

What is the difference between simple elaboration?

1 <script type= "Text/javascript" >2   <!--3     p (); 4      function p () {5          alert (' function declaration '); 6     }7   /--8   </script>

Using a function declaration, there is no problem with this call, because JavaScript has a ' function declaration elevation '. However, the definition of Var p=function () {} will go wrong because the function cannot be found (there is no function declaration elevation);

Some features of the 2 function:

(1) Function object instance

Function names are pointers, functions are objects, so functions are not overloaded;

<script type= "Text/javascript" >   function A () {alert (' a ');}    function A () {alert (' 123 ');}    </script>

results: The 123 is simple: the second function and the first function are different objects, a now points to it, no longer points to the first function object, and the nature of the access is the first function.

(2) since it is an example: Then there will be methods and properties---to have this consciousness

For example, caller can get a reference to the function that called the function; Take a look at the following code

1         function A () {2          B (); 3      }4      function  B () {5        alert (b.caller); 6      }7      A ();//function A () {B ();}

(3) Two important internal properties Arguments,this

This does not have to say, who calls this function on behalf of WHO, note: The function is bound to have the caller, it is not possible to invoke itself.

Arguments is an object used to store function parameters, an object that has a property called callee, representing the function that owns the arguments, in other words, a running function reference

Take a look at the following code

   function C () {        alert (Arguments.callee);   }   C (); // function C () {//code}

3 Defining variables in functions

Defining variables can be so var x=1; x=0; there is no var declaration, there is basically no difference in window global, but the function is not the same; in a word, the Var statement

is the local variable, does not declare that is the variable of window (global variable); Look at the following code

1 function d () {2       name= ' window name '; 3     }4    D (); 5     alert (window.name);//window name

the 2nd line is changed to var name= ' window name ' 5th line error, undefined

The basics of function expressions are almost there, and the next point comes!

4 Scope Chain

Understanding the scope chain is the key to understanding closure;

(1) What is the execution environment

There are two execution environments: Global execution environment, local execution Environment---function inside;

When the execution flow enters function execution, the execution environment is created, and the function execution is finished.

(2) Variable object

It is important to understand the variable object, which is also called the active object in the function, and I prefer to say it as a variable object.

Each execution environment has a variable object, and the variable object saves the variables and methods of the execution environment; it's not hard to imagine who the global variable object is. Window object

We add variables and methods to the global to be added to the window. The variable object is created in the execution environment when the function executes, generally speaking: the execution environment (out of the stack) or the variable object are recycled after the function call is complete. The occurrence of closures makes variable objects not recycled;

(3) Scope chain?

What is a scope chain: the essence of a scope chain is an ordered set of pointers to a variable object; it's literally hard to understand, I don't understand it for the first time!

What it does: order (correct) access to variables and methods in an execution environment;

When created: A function declaration is created and the scope chain is stored in the internal properties of a function [[Scope]];

Note: The Execute Stream entry function is to create the execution environment, copy the scope chain (leveraging the [Scope] property) to the execution environment, create a Variable object (active object), import the reference (pointer) of the variable object into the scope chain, Execute code

See the code below for details

1         functionCompare (value1,value2) {2          if(value1<value2) {return1;}3          Else if(value1>value2) {return-1;}4          Else{return0;}5       }6       varResult=compare (5,10)//1

Scope Chain plot

We can see what the scope chain is: An ordered pointer, the front-most front-end of the scope is the 0 position in the diagram. Looking for a variable or function is the most front-end start, 0 points to the active object is not the variable you are looking for, then go to 1 to find. 0-1 actually

From the point of view of the code is actually from inside the function of the function to find the identifier (variable or function), find immediately stop, no longer look up. This is the scope chain!

5 Closures

Definition: A closure is a function that has access to another function-scoped variable; Notice that the closure is a function!

The main way to create closures is to create a function (closure) within a function, for example:

<script type= "Text/javascript" >    function  A (value) {     var num=value;     function() {//Closure     alert (num);  }}
var B = A (0);
Alert (B ()); 0</script>

Here the anonymous function is a closure, in general: After a function is executed, both the scope chain and the variable object are recycled, but there is a reference to the A () variable object in the scope chain of the anonymous function, so it is not eliminated.

You can also access num for the variable object, which is the benefit of closures! But the advent of closures increased the memory burden, just here, even if we no longer use the B function, a () variable object will not disappear, JavaScript does not know when you will use again, of course, we can b=null; In this way, anonymous functions are not referenced, recycled, and A () variable object is also recycled!

in JavaScript advanced programming, Nicholas recommends that we do not use closures as much as possible, but use them only as a last resort!

6 block-level scopes

We all know that JavaScript does not have block-level scopes, such as {}; if (i=0) {} while () {} for () {} None of these will form a block-level scope, then how do you create a block-level scope for Java C # similar functionality?

Grammar:

(function () {

Block-level scopes

})();

Note: We create an anonymous function that is called immediately, and the code inside is run again, and invisible in the window, isn't that a block-level scope? There is also a benefit that this anonymous function has no pointers,

After the call is recycled, no garbage is generated (the method inside, the variables do not need to be accessed again). This is the perfect block-level scope! Note that the format (anonymous function) is actually a pointer, plus () is called.

7 Closures in constructors

(1) We know how to add a ' private variable ' to an object.

1    function Person (name,age) {2     this. name=name; // Common Attributes 3     this. age= age; 4     5     var // Private Properties 6     this. getschool=function () {return  School;} 7 }

Our school is a private variable, because the object instance can access the variable naturally because of the closure; such as Var p=new person (' nos ', 20); P.getschool (); a medium;

(2) Now come a wonderful flower: static private property;

(function(){         varSchool= "";//static private; Person=function(Name,age,value) {//constructor This. name=name; This. age=Age ; School=value; }; Person.prototype.GetSchool=function() {alert (school);}      })(); varp=NewPerson (' Andy ', 21, ' one '); P.getschool ();//One invarpp=NewPerson (' nos ', 29, ' two '); Pp. Getschool ();//two medium p.getschool ();//Two medium

from the results, school is a common, private property, that is, static private property;

Let's see how the constructor is defined: No var is used, as mentioned earlier, even if the function is defined, without using the Var declaration, the window is the global one. Nature can be used globally!

This anonymous function is called once, and only one object variable is generated, and the school are all the same for sharing.

function expressions and closures

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.