JavaScript BASICS (6) function expression closure _ javascript skills

Source: Internet
Author: User
This article mainly introduces the relevant information about function expression closures in javascript BASICS (6). For more information, see the reasons why javascript supports function closures. The stored data here is only the value of the variable in the function after the function stops running. As for why js needs to store data in functions, JavaScript is a functional language. Saving data in a function is a major feature of a functional language.

Review the three methods of defining functions described above

Functiosu (numnumreturnunum // function declaration syntax definition
Vasufunction (numnum) returnunum} // function expression Definition
VasuneFunction ("num" "num" "returnunum") // Functio Constructor

Before analyzing the closure, let's take a look at the mistakes that are easy to make when defining and calling functions.

Example 1:

SayHi (); // error: var sayHi = function () {alert ("test ");};

Example 2:

If (true) {function sayHi () {alert ("1") ;}} else {function sayHi () {alert ("2") ;}} sayHi (); // printing the result is not what we want

Example 3:

Var fun1 = function fun2 () {alert ("test");} fun2 (); // error: the function does not exist

In example 1, we cannot call a function before defining it using the function declarative syntax. Solution:

1. If a function expression is used to define a function, it must be called after the expression is defined.

var sayHi = function () {  alert("test");};sayHi()

2. Use the function declaration. (Here, the browser engine will improve the function declaration and read the function declaration before all code is executed)

sayHi(); function sayHi () {  alert("test");};

In Example 2, the expected result is print 1, and the actual result is print 2.

If (true) {function sayHi () {alert ("1") ;}} else {function sayHi () {alert ("2") ;}} sayHi (); // printing the result is not what we want

Why? Because the function declaration is upgraded, the browser does not determine the if condition during pre-resolution, and directly resolves the second function definition to overwrite the first one.

Solution:

var sayHi;if (true) {  sayHi = function () {   alert("1");  }  } else {  sayHi = function () {   alert("2");  }}sayHi();

In Example 3, it is found that only fun1 () can be called, rather than fun2.

I do not know why. No information found.

Because 1: function fun3 () {}; is equivalent to var fun3 = function fun3 (){};

Therefore, you can only use fun1 () instead of fun2.

In fact, I still have questions here? Which of the following gods knows.

Since fun2 cannot be called outside, why can it be called inside the function? Although fun1 is still not available in debugger.

Well, warm up with the above three questions. Let's continue with the theme "closure" today ".

1. What is a closure?

Definition: a function that has the right to access variables in another function scope.

Let's start with an example function:

Example 1:

Function fun () {var a = "James";} fun (); // after we run the command, variable a is marked as destroyed.

Example 2:

Function fun () {var a = "James"; return function () {alert ("test") ;}} var f = fun (); // Similarly, after execution, variable a is marked as destroyed.

Example 3:

Function fun () {var a = "James"; return function () {alert (a) ;}}var f = fun (); // [the situation has changed, if a is destroyed, it is clear that f is called and the value of variable a cannot be accessed.] f (); // [the value of variable a is normally accessed] // This is the closure. When function B returned by function A uses the variable of function, then function B uses the closure. Example: function fun () {var a = "James"; return function () {alert (a) ;}} var f = fun (); // [the current situation has changed. If a is destroyed, it is clear that f cannot access the value of variable a if f is called.] f (); // [the value of variable a is normally accessed]

Obviously, misuse of closures will increase memory usage. Therefore, do not use closures unless otherwise specified. If it is used, remember to manually set a null reference before the memory can be recycled f = null;

Illustration: (if you do not know the scope chain, please first read the scope and scope chain of the previous Article)

2. What is an anonymous function? (Just to explain this concept)

For example: (that is, a function without a name)

This is a strange phenomenon when the return value of a function in an object is an anonymous function.

Before explaining this, you should be clear-headed and do not get confused. If you are confused, ignore the following.

Var name1 = "Zhang San"; var obj = {name1: "Li Si", fun2: function () {alert (this. name1) ;}, fun3: function () {return function () {alert (this. name1 );}}}

Obj. fun2 (); // print the result "Li Si" expected.
Obj. fun3 (); // because a function is returned here, we need to add a pair of () calls. The printed result is "James", unexpected.
// What does this point to the global structure?
As we mentioned earlier, "which object is the method of vertices out, and this is the object", so our obj. fun3 () Prints "Michael", that is, this executes the global scope.

Let's take a look at the following example to see why.

Var name1 = "Zhang San"; var obj = {name1: "Li Si", fun2: function () {alert (this. name1) ;}, fun3: function () {return function () {alert (this. name1) ;}}// obj. fun3 (); var obj2 ={}; obj2.name1 = "test"; obj2.fun = obj. fun3 (); obj2.fun (); // print the result "test", which proves again the "method of which object is clicked, this is the object ". var name1 = "Zhang San"; var obj = {name1: "Li Si", fun2: function () {alert (this. name1) ;}, fun3: function () {return function () {alert (this. name1) ;}}// obj. fun3 (); var obj2 ={}; obj2.name1 = "test"; obj2.fun = obj. fun3 (); obj2.fun (); // print the result "test", which proves again the "method of which object is clicked, this is the object ".

Let's break down obj. fun3 () First obj. fun3 () returns an anonymous function to the window scope, and then calls this to point to the window. (I feel a little reluctant to explain, and I don't know if I do. I understand this for the time being)

Causes of closure formation: memory release Problems

Generally, after the function is executed, the partial activity object is destroyed, and only the global scope is saved in the memory, but the closure is different.

The active object of the closure will still be stored in the memory. As in the above example, after the function call returns, variable I belongs to the active object, that is, its stack zone has not been released, but when you call c (), the scope chain saved by the I variable goes from B ()-> a ()-> globally to find the scope var I Declaration, then find var I = 1; then in the closure + I; result, the final output value is 2;

The above is the function expression closure in the basic JavaScript Article (6), which I hope everyone will like.

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.