Home  >  Article  >  Web Front-end  >  JavaScript function scope chain analysis_javascript skills

JavaScript function scope chain analysis_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:14:131021browse

This article analyzes JavaScript function scope chain with examples. Share it with everyone for your reference. The specific analysis is as follows:

Scope chain:

Each function in JavaScript has its own scope, which is saved using the Active Object (AO) active object. A scope chain is formed in the mutually nested functions, as shown in the figure below:

The scope chain is the AO chain from inside to outside

Search for variables:

If the variables used in function fn3 cannot be found in the fn3 scope, they will be found in the outer fn2 scope, and so on, until the global object window

The code demonstration is as follows:

var c = 5; 
function t1(){ 
  var d = 6; 
  function t2(){ 
    var e = 7; 
    var d = 3;
 //如果在这里声明的var d = 3,
 //那么函数就不在向外寻找变量d,输出的值为15 
    console.log(c+d+e); 
  } 
  t2(); 
} 
t1();

After understanding the JavaScript scope chain, it is best to save the external variables as local variables before operating the frequently used external variables in the function. This will greatly reduce the time of searching for variables through the scope chain. .

I hope this article will be helpful to everyone’s JavaScript programming design.

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