JavaScript functions and closures

Source: Internet
Author: User

1.arguments[] objects in function code, using special object arguments, developers can access them without explicitly pointing out the parameter names . You can also use the arguments object to detect the number of parameters of a function, referencing a property arguments.length

The length property of the 2function object ECMAScript the property defined by length declares the number of arguments the function expects

3Function objects also have the ValueOf () method and the ToString () method shared with all objects. Both methods return the source code of the function, which is especially useful when debugging

4 Closures:

When to use closures:
1. When you need to access variables inside a function outside of a function (that is, after the function has run, you want to save the variable and call it when needed). Instead of being eliminated by the garbage collection mechanism (garbage collection)).
2. Protect variable security. An internal variable of a function that can only be referenced by an intrinsic function.

How to define closures: within a function, define a function and return a reference to a function.

3. Look at the two types of closures:

The first form of:

function outer () {
var i = 7;

function inner () {

alert (i);

}

Inner (); can use Setinteval (inner,5000), implement inner function once every 5 seconds

}

The second form of:

function outer () {

var i = 7;

function inner () {

alert (i);

}

return inner (); A function is a special object that returns a reference to a function directly

}

var f = outer (); Use F to accept a reference to the inner layer function returned

f (); Calling the inner layer function

In the first case: The outer function defines the local variable i, the function inner (), and then calls the inner function. Note that the inner () function does not define the variable i in the inner function, which is a local variable from the outer function. When the inner function is referenced, because the inner function of the inner layer requires the use of the variable I, the runtime-defined variable I cannot be freed so that the value of the variable can be obtained when the inner () function executes.

In the second case: after executing the outer () function, a reference to the inner () function is returned, since the external variable f references the intrinsic function inner (), because the inner () function also needs to use the variable i, the local variable i is also referenced by the external variable F, Therefore, the variable I still cannot be released. The difference from the first form is that we can then outer () the value of the variable I after the function is executed. If we will alert (i); Change to alert (++i); So outside of the function, we execute f (); At this time the variable i is not released, the result should be 8, if you call again F (); The result becomes 9. However: if we call outer () again, the function will create a new local variable and then call F (); The result turns out to be 8. This means that as long as the outer function does not create a new variable again, the original variable I will always be valid.

4 closures can be used in many places. Its maximum usefulness is two, one of the variables mentioned above that can read inside a function, and the other is to keep the values of these variables in memory at all times.

How to understand this sentence? Take a look at the following code.


JS Code

  Function F1 () {

var n=999;

Nadd=function () {n+=1}

function F2 () {
alert (n);
}

return F2;

}

var result=f1 ();

Result (); //999

Nadd ();

Result (); // +

In this code, result is actually the closure F2 function. It runs altogether two times, the first value is 999, the second value is 1000. This proves that the local variable n in the function F1 is kept in memory and is not automatically cleared after the F1 call.

Why is that? The reason is that F1 is the parent function of F2, and F2 is assigned to a global variable, which causes F2 to always be in memory, and F2 's presence depends on F1, so F1 is always in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call ends.

Another notable part of this code is the line "nadd=function () {n+=1}", which first did not use the var keyword in front of Nadd, so Nadd is a global variable, not a local variable. Second, the value of Nadd is an anonymous function (anonymous functions), and this

The anonymous function itself is also a closure, so nadd is equivalent to a setter that can manipulate local variables inside the function outside of the function.

4 closure of the attention point:

1) Because the closure will make the variables in the function are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page, in IE may cause memory leaks. The workaround is to remove all unused local variables before exiting the function.

2) The closure changes the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, and the closure as its public method, and the internal variable as its private property (private value), be careful not to arbitrarily change the value of the inner variable of the parent function.

5 closures for application scenarios
Security of variables within the protection function. For example, in the first example, function A can only be accessed by function B, and cannot be accessed by other means, thus protecting the security of I.

  1. Maintains a variable in memory. Still as in the previous example, because of the closure, the function A in the I has been in memory, so each execution C (), will give I self plus 1.
  2. Safe implementation of the protection variable JS private properties and private methods (cannot be accessed externally)
    private properties and methods are not accessible outside of constructor

    function constructor (... ) {  
      var That = this ;  
      var MemberName = value; 
      function membername (... ) {...
    } /span>

The above 3 points are the most basic application scenarios for closures, and many of the classic cases originate from this.

6JavaScript garbage collection mechanism

In JavaScript, if an object is no longer referenced, the object is recycled by the GC. If two objects are referenced by each other and are no longer referenced by the 3rd, then the two mutually referenced objects are also recycled. Because function A is referenced by B and B is referenced by a c outside of a, this is why function A is not recycled after execution.

JavaScript functions 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.