Detailed description of Javascript context and scope

Source: Internet
Author: User

Detailed description of Javascript context and scope

This article attempts to explain the mechanism behind the context and scope in Javascript, mainly involving execution context), scope chain), closure ),this.

Execution context

Execution context (context) determines the variables, functions, and data that can be obtained during Js execution. A program may be divided into many different contexts, each context is bound to a variable object (variable object), which is like a container used to store all the variables and functions that have been defined or can be obtained in the current context. The context at the top or outermost layer is called the global context. The global context depends on the execution environment, suchglobalAndwindow:

 

Note that the context and scope are different concepts. Js itself is a single process. Every time a function is executed, a new context is generated, which is pushed to the context stack of Js, the function is popped up after the execution is complete. Therefore, the Js interpreter is always executed in the context on the top of the stack. When a new context is generated, the variable object of the context is bound first, includingargumentsAnd the variables defined in the function. Then, the scope chain of the context will be created .)thisAssign the Object to which the function belongs. This process can be represented:

This

As mentioned abovethisThe Object to which the function belongs. Specifically, when a function is defined in a global pair,thisPoint to global. When a function acts as the Object method,thisPoint to this Object:

 
 
  1. var x = 1; 
  2. var f = function(){ 
  3.   console.log(this.x); 
  4. f();  // -> 1 
  5.  
  6. var ff = function(){ 
  7.   this.x = 2; 
  8.   console.log(this.x); 
  9. ff(); // -> 2 
  10. x     // -> 2 
  11.  
  12. var o = {x: "o's x", f: f}; 
  13. o.f(); // "o's x" 

As mentioned above, when a function is executed to generate a new context, the variable object of the current context is bound before the scope chain is created. We know that the function definition can be nested in the context created by other functions, or horizontally defined in the same context such as global ). In fact, the scope chain concatenates all variable objects bound to the context of the nested definition from the bottom up so that the nested function can "inherit" the variables of the upper context, the parallel functions do not interfere with each other:

 
 
  1. var x = 'global'; 
  2. function a(){ 
  3.   var x = "a's x"; 
  4.   function b(){ 
  5.     var y = "b's y"; 
  6.     console.log(x); 
  7.   }; 
  8.   b(); 
  9. function c(){ 
  10.   var x = "c's x"; 
  11.   function d(){ 
  12.     console.log(y); 
  13.   }; 
  14.   d(); 
  15. a();  // -> "a's x" 
  16. c();  // -> ReferenceError: y is not defined 
  17. x     // -> "global" 
  18. y     // -> ReferenceError: y is not defined 

Closure

If you understand the context and scope chain mechanism mentioned above, you can see the concept of closure clearly. When a function is called, a new context and scope chain are created, and the scope chain is to concatenate the variable objects bound to the outer upper layer) context one by one, this allows the current function to obtain the variables and data of the outer context. If we define a new function in the function and return the inner function as the value, the scope chain contained in the inner function will be returned together, even if the inner function is executed in other contexts, the internal scope chain still maintains the original data, and the current context may not be able to obtain the data in the original outer function, so that the internal scope chain of the function is protected, to form a closure ". See the following example:

 
 
  1. var x = 100; 
  2. var inc = function(){ 
  3.   var x = 0; 
  4.   return function(){ 
  5.     console.log(x++); 
  6.   }; 
  7. }; 
  8.  
  9. var inc1 = inc(); 
  10. var inc2 = inc(); 
  11.  
  12. inc1();  // -> 0 
  13. inc1();  // -> 1 
  14. inc2();  // -> 0 
  15. inc1();  // -> 2 
  16. inc2();  // -> 1 
  17. x;       // -> 100 

Shows the execution process,incThe scope chain generated when the anonymous function returned internally is created includesincInx, Even if it is assignedinc1Andinc2Thenglobal contextTheir scope chain is still determined by the context in the definition.xYesfunction incDefined in, cannot be outerglobal contextChanges to achieve the closure effect:

This in closure

We have repeatedly mentioned that the execution context and scope are actually created and split through the function, whilethisUnlike the scope chain, it is determined by the Object environment in which ** the function is executed **. This is also true.thisThe most confusing and incorrect one. An example is as follows:

 
 
  1. var name = "global"; 
  2. var o = { 
  3.   name: "o", 
  4.   getName: function(){ 
  5.     return this.name 
  6.   } 
  7. }; 
  8. o.getName();  // -> "o" 

Executiono.getName()HourgetNameBoundthisIt is calledo, So nowthis == o; It is easier to confuse with closure:

 
 
  1. var name = "global"; 
  2. var oo = { 
  3.   name: "oo", 
  4.   getNameFunc: function(){ 
  5.     return function(){ 
  6.       return this.name; 
  7.     }; 
  8.   } 
  9. oo.getNameFunc()();  // -> "global" 

In this case, the closure function isreturnThe subsequent call is equivalent:

 
 
  1. getName = oo.getNameFunc(); 
  2. getName();  // -> "global" 

For a more obvious example:

 
 
  1. Var ooo = {
  2. Name: "ooo ",
  3. GetName: oo. getNameFunc () // at this time, this of the closure function is bound to the new Object.
  4. };
  5. Ooo. getName (); //-> "ooo"

Of course, sometimes to avoidthisWhen executed, it is replaced by the following method:

 
 
  1. var name = "global"; 
  2. var oooo = { 
  3.   name: "ox4", 
  4.   getNameFunc: function(){ 
  5.     var self = this; 
  6.     return function(){ 
  7.        return self.name; 
  8.     }; 
  9.   } 
  10. }; 
  11. oooo.getNameFunc()(); // -> "ox4" 

Or forcibly define the executed Object during the call:

 
 
  1. var name = "global"; 
  2. var oo = { 
  3.   name: "oo", 
  4.   getNameFunc: function(){ 
  5.     return function(){ 
  6.       return this.name; 
  7.     }; 
  8.   } 
  9. oo.getNameFunc()();  // -> "global" 
  10. oo.getNameFunc().bind(oo)(); // -> "oo" 

Summary

Javascript is a very interesting language. because many of its features are DOM operations in HTML, it seems random and slightly less rigorous, however, with the development of the front-end and the rise of Node, Js is no longer "toy language" or "CSS extension" in the jQuery era ", the concepts mentioned in this article are confusing or misunderstood for beginners and Js developers who have been overly involved in traditional Web development. I hope this article will be helpful.

The reason for writing this summary is that I shared the Learn javascript in one picture on Github. Some people initially questioned that this is only a syntax table syntax cheat sheet ), it does not involve more in-depth closures, scopes, and other content, but unexpectedly, this project has more than 3000 stars, so it cannot be used.

Related Article

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.