JavaScript Summary 2--function

Source: Internet
Author: User

First, define the function

In JS, functions are also objects, can be assigned to variables, can be used as parameters, you can set properties, and call the method he owns. The ToString () method of the function returns the contents of his full function. He has two definition methods, function expressions, and function declarations. When a function is used as a constructor, the first letter is written! The function declaration is referred to by JS as the front of the scope before the JS run and the variable declaration. A function can be defined inside another function, or it can return a value as a return of another function. Because of the hoisting nature of the variable declaration, it is best to declare all the variables that are likely to be used at the top of the function in the function.

function declaration: ([] enclosed means optional. )

function name ([parameter]) {Functional Body}

function expression:

functions [function name] ([parameter]) {function Body}

For function expressions, (function ([parameter]) {function body} ([parameter])) indicates immediate execution. eg

(function () {
Alert ("1");
}());

Because functions are also objects in JS, you can use constructors to define functions.

var f = new Function ("X", "Y", "Z", "return x + y-z;");
f (2,3,9);

function can enter any number of arguments, and the last string represents the body of the function.

Second, the function of the call

The first is the function name parentheses functionname (), when he is called as an object method, and returns itself, and then can then call again, this is the function of the chain call;

 1  var  x =  ,  3  add:function   () { 4   This . Count ++;  5  return  this   6   7  };  8  // x.count = 4;  

The second is to use the New keyword as a constructor bar, new functionname ();

The third is the use of call (), apply () indirect invocation. Their first parameter is the current function execution context, which is this, and if the first argument is null or undefined, then the default this is window. The arguments that follow the call serve as arguments to the function, and the arguments that follow the apply are placed in an array.

function Test (x, y    , z) {return x + y + Z;} Test.call (null, N/a); Test.apply (null, [+]);

His calling method affects his context of this. If this is the normal function call, the This is the window, if it is a method invocation, this is the object that calls this method, if it is called as a constructor, he will create a new object, then this is the new object he created, if called by call or apply indirectly, This is their first parameter.

Third, function to pass the parameter

JavaScript functions are very advanced in the way they are passed, but they are not rigorous enough and too random. When the number of passes is less than the number of formal parameters of the function, the remaining parameters are undefined, in order to avoid errors, it is best to use | | to the default value.

There is no relationship when passing in the number of extra parameters. Although it is not straightforward to obtain a reference to an unnamed value, the Parameter object solves the problem. In the body of the function, arguments points to the reference to the argument object, which is a class array object, starting with 0, followed by the order in which the parameters are passed in, and redundant as undefined. In arguments there is a callee attribute, he refers to the currently executing function, can call, of course, chaos will produce a dead loop, constantly self-executing themselves.

function Test () {    console.log (arguments[4]);    Console.log (Arguments.callee);     return Arguments[0] + arguments[1] + arguments[2];} Test (+/-); var t = Test; // function as a value to use t (1,2,3,4);

Iv. function as a namespace

If you want to write a reusable JS code to facilitate later use in other projects, then you should put him in a function, because there is no guarantee that the variables you define are the same as the current project's global variables. At this point, the function name acts like a namespace, he turns the global variable into a local variable of the function, and can hide some variables from the global environment.

V. Function scope and scope chain (scope Chain)

The scope of the function determines the life cycle of parameters and variables, visibility, and reduces naming conflicts, providing automatic memory management (GC, garbage collection). In a JS file, including many functions, each function has its own scope, they have a scope chain together. An internal [Scope] property contains a collection of objects in the scope at which the function was created , which is the scope chain of the function. The scope chain is used to look up variables, and it is important to note that variables declared in the function must be var or else he will become global variables. For example:

1 varwindow_x = "Window";2 functionTest () {3     varParentsarg =arguments;4     vartest_x = "Test"; 5     functioninner () {6 Console.log (test_x);7 Console.log (window_x);8         returnParentsarg[0] + parentsarg[1] + parentsarg[2];9     }         Ten     returninner (); One}

Finding a variable

The scope chain of function inner can be regarded as window--->test--->inner. For example, to find window_x, first find the scope of the inner if there is a variable, do not go to the scope chain on the next level (test) lookup, until the identifier is found, if you find the global scope of the window does not have the identifier, then throw an exception: XXX is not Defined. (Goolge Chrome). As you can guess, the darker the identifier is, the slower his search will be, and the window's global variable is always the last to find.

Creation of scope chain (scope Chain): Inner as an example

1.inner is created, his scope chain [[scope]] is populated with a collection of objects in the test scope; When test is created, [[scope]] is populated with a collection of objects of the global scope (window,document ...). The objects in these [[scope]] represent data that can be accessed in this function.

When 2.inner is executed, he creates an internal object called the runtime context, which defines the environment at which the function executes. Each execution of the function creates a new run-time context, which is automatically destroyed when the function finishes executing. A run-time context has its own scope chain [[Scope]],scope includes the objects contained in the Scopechain that run the function (copy the past).

3. When the previous step is complete, a new object called an "active object" is created for the run-time context. He contains all accessible local variables, named parameters, parameter sets, and so on. The activation object is then pushed to the front end of the scope chain, with the same life cycle and scope chain.

At this point, inner's scope chain contains 3 objects, inner's active object, outer's active object, and the Window object.

Six, closed bag closure

Closures are explained in the JavaScript authoritative guide: function objects can be interconnected by scope chains, and variables inside the function body can be stored within the function scope, which is called "closures" in computer science literature. The popular point is that a function is a closed packet.

1. The role of closures

In JS, the function can freely access the global variables, outside the function to access the function of the variable can not be (can use this feature to imitate the private variables of the class ). But the feature of the closure solves this problem, and he can access the local variables inside the function outside .

1 functionouter () {2   varouter_x = 0;3 4 functionInner (i) {5i =typeofi = = "Number"? i:0;6Outer_x + =i;7Console.log ("I'm going to put outer_x +" + i + "=" +outer_x);8   }9 Ten  One   returnInner; A  - } -  the varTest =outer (); -Test (1);//I'm going to put outer_x + 1 = 1 -Test (2);//I'm going to put outer_x + 2 = 3 -Test (3);//I'm going to put outer_x + 3 = 6 +Test (4);//I'm going to put outer_x + 4 = ten -  + functionOuter1 (i) { A   varouter_x = 0; ati =typeofi = = "Number"? i:0; -Outer_x + =i; -Console.log ("I'm going to put outer_x +" + i + "=" +outer_x); - } - varTest1 =Outer1; -Test1 (1);//I'm going to put outer_x + 1 = 1 inTest1 (2);//I'm going to put outer_x + 2 = 2 -Test1 (3);//I'm going to put outer_x + 3 = 3 toTest1 (4);//I'm going to put outer_x + 4 = 4

In this example, outer returns an anonymous function that accesses the local variable of the outer and adds a specified number to it. This can affect the local variables of the outer through the external I. Outer1 also implements the local variable outer_x plus a specified number. Comparing their results, it can be found that in a function with closures, his variables are not recycled by the garbage collection mechanism (GC). The closure can also be used to keep some local variables in memory. need to be careful with memory leaks.

Why not be recycled by GC?

The outer function returned a reference to the inner function to test. The scope chain of the inner includes the active object of the Inner,outer, and the Window object, test externally references the inner, the reference does not let go, the scope chain of inner is not recycled by GC, and because the inner scope chain contains the outer activation object, Local variables that are in the outer scope chain will naturally not be recycled by GC.

2. Multiple closures in the same scope

If there are multiple closures in the same scope chain, they share the same local variable. And the scope chain associated to the closure is active. For example, I want to create 10 closures in a function.

 function   Test () { var  arr = [];  for  (var  i = 0; i <; I++ = function   () { return   I; }}  return   arr;}  var  arr = Test ();  var  i = 0;  while     (I<10 + ":" + arr[i++

You can find the returned ARR array, each of which is 10. Why? Because when I execute var arr = Test (), I = 10, all closures share this I. Nested functions He does not copy a local variable within the scope. Arr[i] I is not affected because this I belongs to the local variable of test and is not in the nested function. How can you use closures to achieve the desired effect?

There are 2 ways, the first is to change the variable i into a global variable, because this method will pollute the global variables, and not good.

var i = 0function  Test () {    var arr = [];      for (; i <; i++) {        function(        ) {return  i;        }    }     return  arr;}    

The second method is to have the closure function execute immediately and return the current value to the local variable of the external function.

 function   Test () { var  arr = [];  for  (var  i = 0; i <; I++ = (function   () { Span style= "color: #0000ff;"        >return   I;    })();  return   arr;}  var  arr = Test ();  var  i = 0;  while  (I<10 + ":" + arr[i++ 
View Code

3. Context of the closure this

It is clear from the following example that a function is nested within the function, whether in a normal function or in a method, whose context is window.

varName = "the window"; varMyObject ={name:"My Object", Getthis:function() {Console.log ("Method:" + This. name);//method: My Object      return function() {Console.log ("Closure in method:" + This. name);//closure in method: the Window}; }   }; Myobject.getthis () ();functionouter () {varName = "Outername"; functioninner () {//return this.name//the Window    returnName//Outername  }  returnInner;} Console.log ("Closure of the normal function:" + outer ());

JavaScript Summary 2--function

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.