A brief overview of scope and context usage in JavaScript

Source: Internet
Author: User
Tags anonymous arrays bind closure inheritance

  Below is a comprehensive revelation of the differences in context and scope in JavaScript and how various design patterns use them, and interested friends don't miss

The scope and context (contexts) in JavaScript are unique to the language, thanks in part to the flexibility they bring. Each function has a different context and scope of variables. These concepts are backed by some powerful design patterns in JavaScript. However, this also brings a lot of confusion to the developers. The following is a complete revelation of the context and scope in JavaScript and how various design patterns use them.     Context vs scope     The first problem to be clarified is that context and scope are different concepts. Over the years I've noticed that many developers confuse the two terms, incorrectly describing one as another. In all fairness, these terms have become very confusing.     Each function call has a scope and context associated with it. Fundamentally, scopes are based on functions (function-based) and contexts are object-based (object-based). In other words, the scope is related to the access of the variable every time the function is called, and each invocation is independent. The context is always the value of the keyword this, and is a reference to the object that invokes the current executable code.     Variable scopes     variables can be defined in local or global scope, which results in the access of Run-time variables from different scopes. Global variables need to be declared outside of the function body and exist throughout the run, and can be accessed and modified in any scope. Local variables are defined in the function body only, and each function call has a different scope. This topic is an assignment, evaluation, and manipulation of values only in calls that cannot access values outside the scope.     Currently JavaScript does not support block-level scopes, and block-level scopes define variables in statement blocks such as if statements, switch statements, and circular statements, which means that variables cannot be accessed outside the statement block. Any variable currently defined in a statement block can be accessed outside of a statement block. However, this situation will soon change and the LET keyword has been formally added to the ES6 specification. Use it instead of the VAR keyword to declare a local variable as a block-level scope. The     "This" context     context usually depends on how a function is invoked. When a function is invoked as a method of an object, this is set to the object:    code that invokes the method as follows: var object = {  foo:function () {  alert (This = = object); &nb Sp } };    Object.foo (); true    The same principle applies when a function is invoked to create an instance of an object through the operator of new. When invoked this way, the value of this is set to the newly created instance:  code as follows: function foo () {  alert (this); }    foo ()//window  N EW foo ()//foo    When an unbound function is called, this is set to the global context or Window object (if in the browser) by default. However, if the function is executed in strict mode ("use strict"), the value of this will be set to undefined by default.   Execution context and scope chain     JavaScript is a single-threaded language, which means that only one thing can be done in the browser at the same time. When the JavaScript interpreter initially executes the code, it defaults to the global context first. Each call to a function creates a new execution context.     There is a lot of confusion here, the term "execution context" here is meant to be scoped, not the context of the previous discussion. Execution This is the name of the slot cake, however, the term ECMAScript defined by the specification, and helplessly complied with it.     Each time a new execution context is created, it is added to the top of the scope chain and is also an execution or call stack. The browser always runs at the current execution context at the top of the scope chain. Once completed, it (the current execution context) will be removed from the top of the stack and the control will be returned to the previous execution context. For example, the:  code is as follows: function A () {  second ();  function second () {  third ();  function third () {  Fourth ();  function Fourth () { //Do something } } } }  First ();    run front The code will cause nested functions to fall from the top until the fourth function, at which point the scope chain goes from top to bottom: Fourth, third, SECond, a, global. The fourth function is able to access global variables and any variables defined in the First,second and third functions just as you would access your own variables. Once the fourth function completes, the fourth Halo happy context is removed from the top of the scope chain and execution is returned to the Thrid function. This process continues until all code has completed execution.     Variable naming conflicts between different execution contexts are resolved by climbing the scope chain, from local to global. This means that local variables with the same name have a higher priority in the scope chain.     Simply put, every time you try to access a variable in a function execution context, the lookup process always starts with its own variable object. If the variable you are looking for is not found in your own variable object, continue searching the scope chain. It will climb the scope chain to examine the variable object of each execution context to find the value that matches the variable name.     closures     When a nested function is accessed outside the definition (scope), it can be executed after the external function returns, at which point a closure is formed. It (closures) maintains (in internal functions) access to local variables, arguments, and function declarations in external functions. Encapsulation allows us to hide and protect the execution context from an external scope and expose the public interface for further operation through the interface. A simple example looks like the following:  copy code code as follows: function foo () {  var local = ' private variable ';  return function bar () {  re Turn local; } }    var getlocalvariable = foo ();  getlocalvariable ()//Private variable    The most popular type of closures is the well-known modular model. It allows you to simulate public, private, and privileged members:    code as follows: var Module = (function () {  var privateproperty = ' foo ';    function p Rivatemethod (args) { //do something }    return {    PUBlicproperty: "" ",    publicmethod:function (args) { //do something },    Privilegedmethod:function (args) {  privatemethod (args); } } }) ();    modules are actually similar to a single example, Add a pair of parentheses at the end and execute immediately when the interpreter is explained (function is immediately executed). The only available member outside of the closure execution level is the method and property (such as Module.publicmethod) that are common in the return object. However, all private properties and methods will exist throughout the life cycle of the program, and because (closures) enable the execution context to be protected, the interaction with the variables is passed through a common method.     Another type of closure is called an immediate call function expression (immediately-invoked function expression iife), nothing more than a self invocation anonymous function in the window context ( self-invoked anonymous function).   Code as follows: function (window) {    var a = ' Foo ', B = ' bar ';    function private () { //Do Somethi ng }    window. Module = {    public:function () { //Do something } };   }) (this);    protection Global namespaces, this expression is useful, all variables declared in the function body are local variables and are persisted throughout the running environment through closures. This way of encapsulating the source code is very popular with both the program and the framework, often exposing a single global interface interacting with the outside world.     Call and apply    These two simple methods, built into all functions, allow functions to be executed in a custom context. The call function requires a parameter list and the Apply function allows you to pass parameters to the array:    code as follows: FUnction User (I, last, age) { //Do something }  user.call (window, ' John ', ' Doe ',);  user.apply (window, [' John ', ' Doe ',]);    Execution results are the same, the user function is invoked on the window context and provides the same three parameters.     ECMAScript 5 (ES5) introduced the Function.prototype.bind method to control the context, which returns a new function (the context) that is permanently bound to the first parameter of the Bind method, regardless of how the function is invoked. It is the context of the closure correction function, and the following is the scenario:  for unsupported browsers: if (! Bind ' in Function.prototype) "{  Function.prototype.bind = Function () {  var fn = This, context = arguments[0], AR GS = Array.prototype.slice.call (arguments, 1);  return function () {  return fn.apply (context, args); }& nbsp } }    It is commonly used in context loss: object-oriented and event handling. This is necessary because the AddEventListener method of the node always retains the context of the function execution for the event-handling bound node, which is important. However, if you use advanced object-oriented techniques and need to maintain the context of the callback function as an instance of the method, you must manually adjust the contexts. This is the convenience of bind.:  code is as follows: function MyClass () {  this.element = document.createelement (' div ');  This.element.addEventListener (' Click ', This.onClick.bind (this), false); }    MyClass.prototype.onClick = Function (E) { /do something };    When reviewing the source code of the BIND function, you may notice a relatively simple line of code that invokes the array in a method:  code as follows: Array.prototype.slice.call (arguments, 1);    Interestingly, it is interesting to note that the arguments object is not actually an array, but it is often described as an array of classes (array-like object, very much to the result returned by the NodeList (document.getElementsByTagName () method). They contain lenght attributes, values can be indexed, but they are still not arrays because they do not support native array methods such as slice and push. However, because they have arrays of similar behaviors, the array method can be invoked and hijacked. If you want to do this, execute the array method in the context of the class array, referring to the example above.     This technique for invoking other object methods is also applied to object-oriented, when imitating classic inheritance (class inheritance) in JavaScript:  code is as follows: MyClass.prototype.init = function () {  //Call the superclass Init method in the "MyClass" instance  MySuperClass.prototype.init.apply (This, arguments); }    by invoking a superclass (Mysuperclass) in an instance of a subclass (MyClass), we can reproduce this powerful design pattern.     Conclusion     It is important to understand these concepts before you begin to learn advanced design patterns, because scopes and contexts play an important and fundamental role in modern JavaScript. Whether we talk about closures, object-oriented, and inheritance or various native implementations, contexts and scopes play an important role. If your goal is to master the JavaScript language and get a deeper understanding of its composition, the scope and context should be your starting point.     Translator Supplement     The BIND function implemented by the author is incomplete, and the following code fixes this problem by calling the function returned by bind without passing parameters:  &nbsP The code is as follows: if (! Bind ' in Function.prototype) "{  Function.prototype.bind = Function () {  var fn = This, context = arguments[0], AR GS = Array.prototype.slice.call (arguments, 1);  return function () {  return fn.apply (context, Args.concat ( arguments));//fixed } } } 

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.