Home >Web Front-end >JS Tutorial >A brief overview of scope and context usage in JavaScript_Basics

A brief overview of scope and context usage in JavaScript_Basics

WBOY
WBOYOriginal
2016-05-16 17:10:27816browse

Scope and context in JavaScript are unique to the language, thanks in part to the flexibility they bring. Each function has different variable context and scope. These concepts underlie some powerful design patterns in JavaScript. However, this also brings great confusion to developers. The following comprehensively reveals the differences between context and scope in JavaScript, and how various design patterns use them.

Context vs Scope

The first thing that needs to be clarified is that context and scope are different concepts. Over the years I've noticed that many developers often confuse these two terms, incorrectly describing one as the other. To be fair, these terms have become very confusing.

Each function call has a scope and context associated with it. Basically, scope is function-based and context is object-based. In other words, scope is related to the access of variables on each function call, and each call is independent. The context is always the value of the keyword this, which is a reference to the object that calls the current executable code.

Variable Scope

Variables can be defined in local or global scopes, which results in runtime variable access from different scopes. Global variables need to be declared outside the function body, exist throughout the running process, and can be accessed and modified in any scope. Local variables are only defined within the function body and have a different scope for each function call. This topic is assignment, evaluation and operation of values ​​only within the call, and values ​​outside the scope cannot be accessed.

Currently JavaScript does not support block-level scope. Block-level scope refers to defining variables in statement blocks such as if statements, switch statements, loop statements, etc. This means that variables cannot be accessed outside the statement block. Currently any variables defined within a statement block can be accessed outside the statement block. However, this will soon change, as the let keyword has been officially added to the ES6 specification. Use it instead of the var keyword to declare local variables as block-level scope.

"this" context

Context usually depends on how a function is called. When a function is called as a method of an object, this is set to the object on which the method is called:

Copy code The code is as follows :

var object = {
foo: function(){
alert(this === object);
}
};

object.foo(); // true

The same principle applies when calling a function to create an instance of an object through the new operator. When called this way, the value of this will be set to the newly created instance:
Copy code The code is as follows:

function foo(){
alert(this);
}

foo() // window
new foo() // foo

When calling an unbound function, this will be set to the global context or window object (if in a 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 at the same time in the browser. When the JavaScript interpreter initially executes code, it first defaults to the global context. Each time a function is called a new execution context is created.

Confusion often occurs here. The term "execution context" here means scope, not the context discussed above. This is poor naming, but the term is defined by the ECMAScript specification and has no choice but to abide by it.

Every time a new execution context is created, it will be added to the top of the scope chain, and it will also become the execution or call stack. The browser always runs in the current execution context at the top of the scope chain. Once completed, it (the current execution context) is removed from the top of the stack and control is returned to the previous execution context. For example:
Copy code The code is as follows:

function first(){
second( );
function second(){
third();
function third(){
fourth();
function fourth(){
// do something
}
}
}
}
first();

Running the previous code will cause the nested functions to be executed from top to bottom until the fourth function. At this time, the scope chain from top to bottom is: fourth, third, second, first, global. The fourth function can access global variables and any variables defined in the first, second, and third functions just like its own variables. Once the fourth function completes execution, the fourth context will be removed from the top of the scope chain and execution will return 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 higher priority in the scope chain.

Simply put, every time you try to access a variable in the function execution context, the lookup process always starts from 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 and examine each execution context variable object to find a value that matches the variable name.

Closure

When a nested function is accessed outside its definition (scope) so that it can be executed after the outer function returns, then A closure is formed. It (the closure) maintains (in the inner function) access to local variables, arguments and function declarations in the outer function. Encapsulation allows us to hide and protect the execution context from the external scope, while exposing the public interface through which further operations can be performed. A simple example looks like this:
Copy the code The code looks like this:

function foo() {
var local = 'private variable';
return function bar(){
return local;
}
}

var getLocalVariable = foo();
getLocalVariable() // private variable

One of the most popular closure types is the well-known module pattern. It allows you to mock public, private and privileged members:
Copy the code The code is as follows:

var Module = (function(){
var privateProperty = 'foo';

function privateMethod(args){
//do something
}

return {

publicProperty: "",

publicMethod: function(args){
//do something
},

privilegedMethod: function(args){
privateMethod(args);
}
}
})();

The module is actually somewhat similar to a singleton, adding a pair of brackets at the end when explaining Execute immediately after the processor has finished interpreting it (execute the function immediately). The only available external members of the closure execution context are the public methods and properties in the returned object (such as Module.publicMethod). However, all private properties and methods will exist throughout the life cycle of the program, because the execution context is protected (closures), and interaction with variables is through public methods.

Another type of closure is called an immediately-invoked function expression IIFE, which is nothing more than a self-invoked anonymous function in the window context.
Copy code The code is as follows:

function(window){

var a = 'foo', b = 'bar';

function private(){
// do something
}

window.Module = {

public: function(){
// do something
}
};

})(this);

To protect the global namespace, This expression is very useful. All variables declared within the function body are local variables and persist throughout the entire runtime environment through closures. This way of encapsulating source code is very popular for both programs and frameworks, usually exposing a single global interface to interact with the outside world.

Call and Apply

are two simple methods built into all functions that allow functions to be executed in a custom context. The call function requires a parameter list and the apply function allows you to pass the parameters as an array:
Copy the code The code is as follows:

function user(first, last, age){
// do something
}
user.call(window, 'John', 'Doe', 30);
user.apply (window, ['John', 'Doe', 30]);

The result of execution is the same, the user function is called on the window context and the same three parameters are provided.

ECMAScript 5 (ES5) introduced the Function.prototype.bind method to control the context. It returns a new function. This function (the context) is permanently bound to the first parameter of the bind method, regardless of the function. How to be called. It corrects the context of the function through closure. The following is a solution for unsupported browsers:
Copy the code The code is as follows:

if(!('bind' in Function.prototype)){
Function.prototype.bind = function(){
var fn = this, context = arguments[0] , args = Array.prototype.slice.call(arguments, 1);
return function(){
return fn.apply(context, args);
}
}
}

It is commonly used in context loss: object-oriented and event processing. This is necessary because the node's addEventListener method always maintains the context of function execution as the node to which the event handler is bound, which is important. However, if you use advanced object-oriented techniques and need to maintain the callback function's context as an instance of the method, you must manually adjust the context. This is the convenience brought by bind:
Copy code The 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 looking back at the source code of the bind function, you may notice that the following line is relatively Simple code, calling a method of Array:
Copy code The code is as follows:

Array. prototype.slice.call(arguments, 1);

Interestingly, it is important to note here that the arguments object is not actually an array, however it is often described as an array-like ) object, which is the result returned by nodelist (document.getElementsByTagName() method). They contain length attributes, and the values ​​can be indexed, but they are still not arrays because they do not support native array methods such as slice and push. However, since they behave similarly to arrays, array methods can be called and hijacked. If you want to execute array methods in an array-like context, follow the example above.

This technique of calling other object methods is also applied to object-oriented, when emulating classic inheritance (class inheritance) in JavaScript:
Copy Code The code is as follows:

MyClass.prototype.init = function(){
// call the superclass init method in the context of the "MyClass" instance
MySuperClass.prototype.init.apply(this, arguments);
}

By calling the method of the superclass (MySuperClass) in the instance of the subclass (MyClass), we can reproduce this powerful design pattern.

Conclusion

It is very important to understand these concepts before you start learning advanced design patterns, since scope and context play an important and fundamental role in modern javascript Role. Whether we talk about closures, object-oriented, and inheritance or various native implementations, context and scope play an important role. If your goal is to master the JavaScript language and gain a deep understanding of its components, scope and context should be your starting point.

Translator’s Supplement

The bind function implemented by the author is incomplete. Parameters cannot be passed when calling the function returned by bind. The following code fixes this problem:

Copy code The code is as follows:

if(!('bind' in Function. prototype)){
Function.prototype.bind = function(){
var fn = this, context = arguments[0], args = Array.prototype.slice.call(arguments, 1);
return function(){
return fn.apply(context, args.concat(arguments));//fixed
}
}
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn