JS series -3 JS Scope and Closure

Source: Internet
Author: User

4, the function scope can be used arguments to get the function arguments,arguments Although it is accessible by subscript, but it is not an array, the prototype is not Array.prototype. It is a copy of the argument, and the overloads of the method can be simulated by arguments.

function Add () {if (arguments.length = = 1) {alert (1);       } if (arguments.length = = 2) {alert (2);       } if (arguments.length = = 3) {alert (3);   }} Add (1);   Add (+); Add (+/-);

5, Scope:

Global, function,eval. JS does not have block-level scopes .

var local0=3;function outer2 () {var local2 = 1;      function Outer1 () {var local1 = 2;   Here you can access the LOCAL1,LOCAL2,LOCAL3.   }}////////newfunction Compare Special////////function outer () {var i = 0; var func = new Function ("Console.log (i)") func (); }outer (); UNCAUGHTREFERENCEERROR:I is not defined

With the function scope, the class library is often written to execute function expressions immediately. The variables declared inside are local and do not cause global pollution.

6, the benefit of scopes is that intrinsic functions can access the parameters and variables of the external function that defines them (except for this,arguments ), and the intrinsic function has a longer life cycle than its external function, which is a closure.

7, closure: An intrinsic function can freely access the parameters and variables of the parent function, and the function object created by the function literal contains a connection to the external context, which is called a closure.

function outer () {      var a  =1;      return function () { return a; }}var func =  outer (); //     variable A is not released Func ();               //even though the outer function execution is still accessible, its variables   closures enable better encapsulation and access to private variables with GetUserName. (function () {   var username=  "Zhang";   var output ={};    output.getusername = function () {      return  Username;   }    window.output = output;} ());    output.getusername ();      "Zhang" output.username;           undefined 

closures can cause a scope environment to not release----space after a function call is complete , or even memory leaks

Save status with closures

As with normal functions, the self-executing function expression can be passed as a parameter, since the closure can directly refer to the parameters passed in and take advantage of these lock -in parameters. Self-executing function expressions can save states effectively.

  This code is wrong, because the variable I never back locked live//  instead, when the loop executes, we click on the time I get the value//  because this time I really get the value//  so say no matter click that connection, The final display is i am link  #10 (if there are 10 a elements) var elems =document.getelementsbytagname (' a '); for   (var i = 0; i< elems.length; i++)  {    elems[i ].addeventlistener (' Click ',  function (e)  {        alert (' I  am link # '  + i);    },  ' false ');} This is possible because the value of// i inside the self-executing function expression Closure is the index of the locked, and after the execution of the loop, even though the value of the last I becomes the total number of a elements (for example, ten)//  But the Lockedinindex value inside the closure is unchanged because he has executed the//  so the result is correct when the connection is clicked Var elems = document.getElementsByTagName (' a ');for  (var i = 0; i< elems.length; i++)  {  (function (lockedinindex)  {   elems[i].addeventlistener (' click ',  function (e)  {      alert (' i am link # '  +lockeDinindex);   },  ' false ');    }) (i); You can also use the self-executing function expression//  instead of the AddEventListener external// , as in the following, but relatively speaking, the above code is more readable var elems = document.getElementsByTagName (' a '); for (var i = 0; i< elems.length; i++)   {    elems[i].addeventlistener (' click ',  (function (lockedinindex)  {       returnfunction (e)  {   e.preventdefault ();         alert (' i am link # '  +lockedinindex);}) (i),  ' false ');}

In fact, the above 2 Examples of the lockedinindex variable can also be replaced with I, because and the outside I is not a scope, so there is no problem, this is also anonymous function + The power of closures.

Bind Method (ES5, bind this, currying):

8, currying:

Functionadd (a,b,c) {return a+b+c;}  var func=add.bind (undefined,100); Func (//103var) Func2 =func.bind (undefined,200); FUNC2 (10); 310

9, Execution Context

Variable object: VO abstract concept, not JS variables in the. Used to store variables in the execution context, function declarations, function arguments.

each time a function executes, it produces an execution context, a VO , the global scope also has an execution context with VO .

VO is an abstract concept and cannot be accessed, but the browser has a global VO set a property window Pointing VO itself. So Window.window.window....===window

The execution of the function is divided into the variable initialization phase and the execution phase.

Variable Initialization phase VO fill in the following order

1, function parameter (if not passed in, initialize the parameter value to undefined )

2, function declaration (overwrite if a naming conflict occurs)

3, Variable declaration (the initialization variable value is undefined , if a naming conflict occurs, it is ignored)

function expressions do not affect VO , which explains why you cannot use the name of a named function expression to access it.

alert (x);          Functionvar x = 10;alert (x);           10x=20;function x () {};alert (x); 20if (True) {var a = 1;} else{var B = true;}       alert (a);       1alert (b); Undefined

The execution context is a stack.

JS series -3 JS Scope and Closure

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.