A thorough understanding of JavaScript scope

What is the scope?

  Almost all of the programming language is the value stored in the variable, and can read and modify this value. In fact, the value stored in the variable capacity and takes a value of, imparting to the program state.
If there is no such concept, although a program can perform some tasks, but they will be severely limited and not very interesting.
But these variables are stored in the where, and gave how to read? To accomplish this goal, the need to develop some rules, this rule is: scope.

Common scope is divided into several types: global scope, function scope, massive scope and dynamic scope.

Objects Types of
global window Global scope
function Function scope (local scope)
{} Massive scope
this Dynamic scope

If a variable or other expression is not "current scope", then the JavaScript will continue to look for mechanisms along the scope chain until the global scope (window global or browser) If you can not find the will can not be used. Scope hierarchical level may be in accordance with the code, so that the child can access the parent scope scope, the scope chain generally refers to locate along the chain, instead of the child from the parent scope reference variable scope and references

Global scope

  Variable or function block {}outside the definition is the global scope. However, the function or block of code {}is not defined in the variable also has a global scope (not recommended).

var carname = " Volvo " ; // here call 
carname variable
function myFunction () {
// the function may be called variable} carname

  The code variable  carName is defined outside the function, which is to have global scope. This variable can be read or modified in any place, of course, if the variable is not declared within a function (not using the var keyword), the variable will still be global variables.

  Here carname variable callable function myFunction () {carName = "Volvo"; // call carname variables here}

  Inside the function or code block variable is actually not defined as an attribute window / global presence, instead of the global variables. In other words there is no variable defined using var, though they have global scope, but it can be delete, and global variables can not.

Function scope

  Variables inside a function definition, is the local scope. Function scope, outside is closed and can not access the scope of the internal function directly from the outer scope!

function bar () {
   were test value = ' internal ' ;
}

console.log(testValue);        // 报错:ReferenceError: testValue is not defined

  If you want to read variable within the function, you must return or closure means.

function bar(value) {
  var testValue = 'inner';

  return testValue + value;
}

console.log(bar('fun'));        // "innerfun" 

  This is by way of return, the following is the way of closure:

function bar(value) {
  var testValue = 'inner';

  was rusult = test value + value;

  function realizes () {
     return rusult;
  };

  return realize ();
}

console.log(bar('fun'));        // "innerfun"

  Popular speaking, return the export function of foreign exchange, and return may be returned by a function, according to the scope of the rules, internal functions Functions are variables that can be obtained within the scope of the function.

Speaking of this fact, I think the scope of the problem nested function, the function again if the inner nested function? This is another concept related to: the scope chain.

  Careful observation on the map, it is not difficult to understand what the scope chain, because you can go to understand that in accordance with the prototype chain. Any scope chain is a stack of a first end of first global scope pushed onto the stack, and then according to a function of a nesting relationship onto the stack. In the course of implementation looks for variables in this scope chain.

Massive scope

  In other programming languages, the massive scope is very familiar with the concept, but is not supported in JavaScript, just like the above knowledge, in addition to the global scope is function scope, has not been their massive scope. In ES6 has changed this phenomenon, the massive scope gained popularity. What is on the block, just know  {} it.

if(true){
  let a = 1
  console.log(a)
}

  In this code,  if 后 {} is "block", the inside of this variable is to have massive scope, according to the rules, {} outside of this variable is not accessible.

Dynamic scope

  In JavaScript, many students point of this is sometimes clear and sometimes vague, in fact, combined with the scope of this will have a clear understanding. You may wish to look at this code:

window.a = 3
function test () {
  console.log(this.a)
}

test.bind({ a: 2 })() // 2
test() // 3

  Here bind have narrowed the scope of the points were modified  { a: 2 }, and this point is the current scope of the object, is not a clear understanding of it?

  Next we ponder another question: when the scope is to write code that has already decided, or are decided in the course of execution of the code in?

var carName = " Volvo";

// here call carName variable 
function myFunction () {
     // the function may be called variable carName 
}

  Take a look at this code, write the code to know carName is global scope inside a function with the var variable is defined function scope. This is the technical term: lexical scope.
Popular speaking variables when defining the scope is determined not decide when to perform, that lexical scope depends on the source code can be determined by static analysis, so the lexical scoping also called static scope.
On the contrary, can only decide the scope of the variables in the implementation phase, that is the dynamic scope.
Consider the following code is to follow the dynamic scope or static scope of it?

function foo() {
    the console.log (A); // 2 (not 3!) 
}

function bar() {
    There are a = 3 ;
    foo();
}

There are a = 2 ;

bar();

  Why is this so?

  If the analysis in accordance with the dynamic scoping: when '() foo can not resolve a reference to a variable, it does not go up the chain along one nested scopes, but take up the call stack to find foo ( ) where is invoked. Check the effect of variables because foo () is called from the bar (), which will be in the bar () domain, and find the value of holding a 3 here.
If you follow static scoping analysis: foo executed when a variable is not found, it will look up the code in the order written, foo is defined in the outer layer, to find var a = 2, instead of calling foo bar looking inside.
So the result is 2.
As can be seen from this example uses the default JavaScript lexical (static) scoping, if you want to turn on dynamic scoping please help bind, with, eval and so on.

Guess you like

Origin www.cnblogs.com/zhoulifeng/p/12088011.html