JavaScript Basics Eight (functions and closures)

Source: Internet
Author: User
Tags variable scope

There are four ways to call 1.function: the ① normal function calls ② as a method call (the function acts as a property of an object) ③ constructor calls the ④call,apply method to invoke the

2.this is the keyword of JavaScript, this has no scope, is related to the function called, or undefined in strict mode. The nested function this does not point to an external function. The following code:

    varo = {//defines an object oM:function() {//add a method to the object M property            varSelf = This;//Keep this point, here this point is OConsole.log ( This);//true            f (); //internal invocation of nested functions            functionF () {//Console.log ( This===window);//"false"Console.log (self);//"true"            }        }    }; O.M ();

It is important to note here that a nested function f () is called inside M, and this is the window, not the o,this is only related to the call, which points to window, which indicates that it looks like a window call. In fact, if changed to WINDOW.F () to call, here will be error WINDOW.F not defined, here need attention.

3.arguments.callee: Points to the currently running function, which can be used when the anonymous function is called recursively, and cannot be used in ES5 strict mode.

    var function (x) {        ifreturn 1;         return x * Arguments.callee (x-1);    };    Console.log (factorial (5)); //  -

4.arguments.caller: This property has been deprecated and should not be used anymore. The function that primarily executes the call.

5. Closures : The combination of a function object and a variable scope that a function contains is a closure. Keywords are function objects and scopes. Technically speaking, all JavaScript functions are closures because they are objects and have scopes. Most function calls are used when defining the scope chain , so it's not very compelling. Closures start with a bit of meaning inside the function nesting, which is usually ignored, because function nesting produces different scopes. One of the most basic principles of understanding closures is that functions are executed using a defined scope chain. For example:

    varScope = "Global scope"; functionCheckscope () {varScope = "Local scope"; functionf () {returnscope; }         return F; } console.log (Checkscope ());//"Local scope" =====================================================varScope = "Global scope"; functionCheckscope () {varScope = "Local scope"; functionf () {returnscope; }         return f (); } console.log (Checkscope ());. "Local Scope"

The results of the above two code execution are the same, indicating that the scope of the closure is only related to the time of definition, it is not related to calling a function inside a function or calling a function outside the function. Whenever we call a function, we create a new object to hold some local variables that need to be used when called. This object (the object bound by the variable) is added to the scope chain, and when the function returns, the object is removed from the scope chain. If there is no other reference to this variable, it will be GC. If a nested function is defined and a nested function is returned, or the nested function is stored in a property. This will have an external reference. , the nested function will not be GC, and the object will not be GC.

6. An example code for closures

    varUniqueInteger1 = (function() {        varCounter = 0; return function() {            returncounter++;    };    }()); varUniqueInteger2 = (function() {        varCounter = 0; return{count:function() {                returncounter++; }, Reset:function() {counter= 0;    }        }; }());

The basis of understanding closure is the lexical scope, the scope of the function call when the function definition is used

7. Length property of the function: Indicates the number of arguments expected by the function at the time of definition (that is, the number of arguments in parentheses)

8.bind method: Binding a function to an object is actually changing the this point of the function, and the Bind method returns a new function. The code is described below:

    functionf (y, z) {Console.log ( This);//Object {x:1}        returnZ? This. x + y + z: This. x +y; }    varo ={x:1    }; varg = F.bind (o, 10);The first parameter is this point, and the following parameter is optional, which is the parameter that assigns a value to the function. Hereassign value to parameter yConsole.log (g ());//Console.log (g (2));//Assigning a value of 2 to a parameter ZConsole.log (G.prototype);//the function returned by undefined bind has no prototype property

9. How the function is defined the new function () and the function keyword. Functions constructed through the new function do not follow the lexical scope, but are global. Try to avoid using

    var fn1=New Function (' x ', ' y ', ' return x+y; ') );     function fn2 (x, y) {return x+y;} // fn1 and fn2 equivalent     Console.log (fn1);    Console.log (fn2);

10. Higher order (High-order) function: Takes a function as a parameter and returns a function.

JavaScript Basics Eight (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.