Function scope and the scope chain

Variable Scope

Global scope

In JavaScript the scope of global variables is relatively simple, its scope is global, anywhere in the code are all defined. However, the function parameters and local variables defined only in the body of the function

1. function outside the defined variables have global scope

var n =2;
function fn() { 
  var a= 1;
  return a;
 }
 console.log(fn())//1
 console.log(n)//2
 console.log(a)//报错 error

 

2 direct assignment of undefined variables are automatically declared as global scope has

var n =2;
function fn() { 
    a= 1;
  return a;
 }
 console.log(fn())//1
 console.log(n)//2
 console.log(a)//1

Property 3.window object has a global role

Local scope

Local scope generally within a fixed code segment may have access to the most common example of internal functions, so in some places will be a function of the scope of this scope.

Figure I, a is declared inside functions and assignments, with local scope, only use with internal functions fn, fn external error will be in use, which is characteristic of local scope, external inaccessible.

The block-level scope 3ES6

ES5 only global scope and function scope, not block-level scope, will bring the following questions:

 

ES6 introduction of block-level scope, explicitly permitted in a statement block-level scope function, let const command and involve block-level scope.

The scope chain

Scope of a function is actually a dynamic concept only when the function is called, will open up a dynamic of its own scope, function calls over the scope and closed in memory, processes running function data in memory has been cleared created

More simply, when a function declaration, a local scope a wrap up, is scope chain.

1. When the function is executed, always start looking for local variables inside a function

2. If you can not find the internal (local scope of a function does not), will be the scope (scope function declaration) to create a function to find, turn up

 

Guess you like

Origin www.cnblogs.com/xcyzkh/p/11311867.html