JavaScript basic article (6) function expression closure _javascript technique

Source: Internet
Author: User
Tags closure function definition memory usage

In fact, the main reason for JS support function closure is because JS requires a function to save data. The saved data here is a function. The value of the variable within the function is also saved after the run is completed. As for why JS needs to save data in a function, that is, JS is a functional language. Saving data within a function is a major feature of a functional language.

Review the three definitions of functional methods described earlier

Functiosu (numnumreturnunum//function declaration syntax definition
Vasufunction (numnum) returnunum}//function expression definition
Vasunefunction ("num" "num" "Returnunum")//functio constructors

Before parsing the closure, let's take a look at the error that is easy to define and invoke the function.

Example 1:

Sayhi (); Error: function does not yet exist
var sayhi = function () {
  alert (' Test ');

Example 2:

if (true) {
  function sayhi () {
    alert ("1");
  }
} else {
  function sayhi () {
    alert ("2");
  }
}
Sayhi ()//print result is not what we want

Example 3:

var fun1 = function fun2 () {
  alert ("test");
}
Fun2 ();//error: Function does not exist yet

In Example 1, we cannot call a function before using a function-declarative syntax definition. Solution:

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

var sayhi = function () {
  alert ("test");
Sayhi ()

2. Use function declaration. (Here the browser engine functions to declare elevation, read the function declaration before all code executes)

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

In Example 2, our expected result would be to print 1, and the actual result would be to print 2.

if (true) {
  function sayhi () {
   alert ("1");
  }
  } else {
  function sayhi () {
   alert ("2");
  }
}
Sayhi ()//print result is not what we want

Why is that? Because the function declaration is promoted, the browser does not judge the IF condition when it is resolved, and overwrites the first one when parsing the second function definition directly.

Solution:

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

In Example 3, Discovery can only be invoked with FUN1 () instead of fun2 ().

My own understanding, the real reason does not know. No information was found.

Because 1:function Fun3 () {}; Equivalent to var fun3 = function fun3 () {}; As shown in figure:

So you can only invoke fun1 () instead of using fun2 () calls.

In fact, I still have questions here? Which great God knows, hope to inform.

Since fun2 cannot be invoked outside, why can it be called inside a function? Although in debugger still can not get fun1.

Okay, warm up with the top three questions. We continue today's topic "Closure".

1. What is closure?

Definition: is a function that has access to a variable of another function scope

Let's start with a sample function:

Example 1:

function Fun () {
  var a = ' John ';
}
Fun ()//After we execute, variable A is marked for destruction.

Example 2:

function Fun () {
  var a = ' John ';
  return function () {
    alert (' Test ');
  }
}
var f = fun ();//Similarly, after we execute, the variable A is marked for destruction

Example 3:

function Fun () {
  var a = ' John ';
  return function () {
    alert (a);
  }
}
var f = fun ();//"Now the situation has changed, if a is destroyed, it is clear that F is invoked without access to the value of variable a"
f ();/"Then the value of variable A is normally accessed"
//This is the closure, when function a returns a function b It uses a variable of function A, then function B uses a closure.
Example:
function Fun () {
  var a = ' John ';
  return function () {
   alert (a);
  }
}
var f = fun ();//"Now that the situation has changed, if a is destroyed, it is obvious that F is called without access to the value of variable a"
f ();/"Then the value of variable A is normally accessed"

Obviously, misuse of closures can increase memory usage. So do not use closures as far as possible in special cases. If used, remember to manually set a null reference, memory can be recycled f = null;

Diagram: (Students who do not understand the scope chain, see the previous article scope and scope chain)

2. What is an anonymous function? (just explain the concept)

such as: (i.e., a function without a name)

The weird behavior of this is when the return value of a function in an object is an anonymous function

Before you explain, clear your head, don't look more confused. If you're confused, just ignore the following.

var name1 = "John";
var obj = {
  name1: "Dick",      
  fun2:function () {
    alert (this.name1);
  },
  fun3:function () {return
    fun Ction () {
      alert (this.name1);
    }
  }
}

OBJ.FUN2 ()//print result "Dick" is expected.
The Obj.fun3 () ()//////////////////////////////// The print result is "John", unexpected.
What is this point to the global?
We've talked before about "which object points out the method, this is which object", then our Obj.fun3 () () prints "John", which means that this performs a global scope.

Let's take a look at the example below and probably know why.

var name1 = "John";
var obj = {
  name1: "Dick",      
  fun2:function () {
    alert (this.name1);
  },
  fun3:function () {return
    fun Ction () {
      alert (this.name1);
    }    
}} Obj.fun3 () ();
var obj2 = {};
obj2.name1 = "Test";
Obj2.fun = Obj.fun3 ();
The Obj2.fun ()///Print result "test" proves again "which object points out the method, this is which object".
var name1 = "John";
var obj = {
  name1: "Dick",
  fun2:function () {
   alert (this.name1);
  },
  fun3:function () {
    return function () {
     alert (this.name1);
    }
}} Obj.fun3 () ();
var obj2 = {};
obj2.name1 = "Test";
Obj2.fun = Obj.fun3 ();
The Obj2.fun ()///Print result "test" proves again "which object points out the method, this is which object".

Let's break Down Obj.fun3 () () first OBJ.FUN3 () returns an anonymous function to the window scope, and then the call to this point to window. (Feel the explanation a bit reluctantly, do not know right no, for the time being I first so understand)

Reasons for Closures: Memory release issues

Generally, when the function completes, the local active object is destroyed, only the global scope is saved in memory, but the case of the closure is not the same.

The active object of the closure is still stored in memory, so like in the example above, when the function call returns, the variable I belongs to the active object, that is, the stack area has not been released, but when you call C (), the scope chain of the I variable is saved from B ()->a ()-> Global to look for scope var I declare the location, then find the Var I=1; then ++i in the closure; the final output value is 2.

The above is small to share the JavaScript basic article (6) of the function expression closure, I hope you like.

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.