Home > Web Front-end > JS Tutorial > body text

Detailed explanation of javascript execution environment and scope_javascript skills

WBOY
Release: 2016-05-16 15:02:05
Original
1390 people have browsed it

I have been re-reading "JavaScript Advanced Programming 3" recently, and I feel that I should write some blogs to record some of the knowledge I have learned, otherwise I will forget it all. What I want to summarize today is the js execution environment and scope.

First let’s talk about the execution environment

1. Execution environment
​​​​​The concept in the book, the execution environment defines variables or other data that functions have access to, and determines their respective behaviors. Each execution environment has a variable object associated with it. All variables and functions defined in the environment are saved in this object. Although we don't have access to this object while writing code, the parser uses it behind the scenes when processing data.

 Execution environment is a concept, a mechanism that defines whether a variable or function has permission to access other data

In javascript, there are three types of executable JavaScript code:
​​​ 1. Global Code, that is, global code that is not in any function, such as: a js file, js code embedded in an HTML page, etc.
​​​​ 2. Eval Code, which is JS code that is dynamically executed using the eval() function.
​​​ 3. Function Code, that is, the function body JS code in the user-defined function.

Skip Eval Code and only talk about the global execution environment and function execution environment.

1. Global environment:

The global environment is the most peripheral execution environment. The global execution environment is considered the window object. Therefore all global variables and functions are created as properties and methods of the window object. When the code is loaded into the browser, the global execution environment is created (the global execution environment is destroyed when we close the web page or browser). For example, in a page, a global execution environment is created when the JS code is loaded for the first time.

This is why closures have the disadvantage of memory leaks. Because the external function in the closure is treated as the global environment. So it will not be destroyed and will always be saved in memory.

2. Function execution environment

Each function has its own execution environment. When execution enters a function, the execution environment of the function will be pushed to the top of an execution environment stack and the execution right will be obtained. When the function completes execution, its execution environment is removed from the top of the stack and the execution rights are returned to the previous execution environment. This is the execution flow in an ECMAScript program.

It can also be interpreted this way: when a JavaScript function is called, the function will enter the execution environment corresponding to the function. If another function is called, a new execution environment is created, and the execution process is in this environment during the function call. When the called function returns, the execution process returns to the original execution environment. Therefore, the running JavaScript code constitutes an execution environment stack.

 The local environment of the function is created when the function is called (after the code within the function is executed, the environment is destroyed, and all variables and function definitions saved in it are also destroyed).

2-1 Definition Period

When a function is defined, a [[scope]] attribute will be created. This object corresponds to a list of objects. The objects in the list can only be accessed within JavaScript and cannot be accessed through syntax.

 (Scope also means scope.)

We define a global function A, then the A function creates a [[scope]] attribute of A. At this time, [[scope]] only contains the global object [Global Object].

And if we define a B function inside A, then the B function will also create a [[scope]] attribute. The [[scope]] attribute of B contains two objects, one is the active object of A Activation Object, one is the global object, A's activity object is in the front, and the global object is in the back.

In short, the order of the object list in the [Scope] attribute of a function is the Activation Object object of the upper layer function, then the upper layer, all the way to the outermost global object.

The following is the sample code: A has only one scope, and B has two scopes

// 外部函数
function A(){
  var somevar;
  
  // 内部函数
 function B(){
   var somevar;
  }
}
Copy after login

2-2 execution period

When a function is executed, it enters the execution environment of this function. First, it creates its own activity object [Activation Object] (this object contains this, parameters (arguments), local variables (including named parameter) and the scope chain [[scope chain]] of a variable object, then copy the [scope] of this execution environment to [[scope chain]] in order, and finally push the active object into [[scope chain]] The top of [scope chain]] is an ordered stack, thus ensuring ordered access to all variables and objects that the execution environment has access to.

// 第一步页面载入创全局执行环境global executing context和全局活动象
// 定义全局[[scope]],只含有Window对象
// 扫描全局的定义变量及函数对象:color【undefined】、changecolor【FD创建changecolor的[[scope]],此时里面只含有全局活动对象】,加入到window中,所以全局变量和全局函数对象都是做为window的属性定义的。
// 程序已经定义好所以在此执行环境内任何位置都可以执行changecolor(),color也已经被定义,但是它的值是undefined

// 第二步color赋值"blue"
var color = "blue";

// 它是不需要赋值的,它就是引用本身
function changecolor() {
 // 第四步进入changecolor的执行环境
 // 复制changecolor的[[scope]]到scope chain
 // 创建活动对象,扫描定义变量和定义函数,anothercolor【undefined】和swapcolors【FD创建swapcolors的[[scope]]加入changecolor的活动对象和全局活动对象】加入到活动对象,活动对象中同时还要加入arguments和this
 // 活动对象推入scope chain 顶端
 // 程序已经定义好所以在此执行环境内任何位置都可以执行swapcolors(),anothercolor也已经被定义好,但它的值是undefined
 
 // 第五anothercolor赋值"red"
 var anothercolor = "red";
 
 // 它是不需要赋值的,它就是引用本身
 function swapcolors() {
  // 第七步进入swapcolors的执行环境,创建它的活动对象
  // 复制swapcolors的[[scope]]到scope chain
  // 扫描定义变量和定义函数对象,活动对象中加入变量tempcolor【undefined】以及arguments和this
  // 活动对象推入scope chain 顶端
  
  // 第八步tempcolor赋值anothercolor,anothercolor和color会沿着scope chain被查到,并继续往下执行
  var tempcolor = anothercolor;
   anothercolor = color;
   color = tempcolor; 
 }

 // 第六步执行swapcolors,进入其执行环境
 swapcolors();
}

// 第三步执行changecolor,进入其执行环境
changecolor();

Copy after login

2-3访问标识符:

  当执行js代码的过程中,遇到一个标识符,就会根据标识符的名称,在执行上下文(Execution Context)的作用域链中进行搜索。从作用域链的第一个对象(该函数的Activation Object对象)开始,如果没有找到,就搜索作用域链中的下一个对象,如此往复,直到找到了标识符的定义。如果在搜索完作用域中的最后一个对象,也就是全局对象(Global Object)以后也没有找到,则会抛出一个错误,提示undefined。

二、Scope/Scope Chain(作用域/作用域链)

  当代码在一个环境中执行时,都会创建一个作用域链。 作用域链的用途是保证对执行环境有权访问的所有变量和函数的有序访问。整个作用域链是由不同执行位置上的变量对象按照规则所构建一个链表。作用域链的最前端,始终是当前正在执行的代码所在环境的变量对象。

  如果这个环境是函数,则将其活动对象(activation object)作为变量对象。活动对象在最开始时只包含一个变量,就是函数内部的arguments对象。作用域链中的下一个变量对象来自该函数的包含环境,而再下一个变量对象来自再下一个包含环境。这样,一直延续到全局执行环境,全局执行环境的Variable Object始终是作用域链中的最后一个对象。

如图所示:

书中例子:

 var color="blue";
 function changecolor(){
 var anothercolor="red";
 function swapcolors(){
 var tempcolor=anothercolor;
 anothercolor=color;
 color=tempcolor;
  // Todo something  
  }
 swapcolors();
}
changecolor();
 //这里不能访问tempcolor和anocolor;但是可以访问color;
alert("Color is now "+color);
Copy after login

  通过上面的分析,我们可以得知内部环境可以通过作用域链访问所有的外部环境,但外部环境不能访问内部环境中的任何变量和函数。

  这些环境之间是线性、有次序的。每个环境都可以向上搜索作用域链,以便查询变量和函数名;但任何环境不能通过向下搜索作用域链条而进入另一个执行环境。

  对于上述例子的swapcolor()函数而言,其作用域链包括:swapcolor()的变量对象、changecolor()变量对象和全局对象。swapcolor()的局部环境开始先在自己的Variable Object中搜索变量和函数名,找不到,则向上搜索changecolor作用域链。。。。。以此类推。但是,changecolor()函数是无法访问swapcolor中的变量

启示:尽量使用局部变量,能够减少搜索的时间

1、没有块级作用域

与C、C++以及JAVA不同,Javscript没有块级作用域。看下面代码:

if(true){
  var myvar = "张三"; 
 }
 alert(myvar);// 张三
Copy after login

如果有块级作用域,外部是访问不到myvar的。再看下面

for (var i=0;i<10;i++){
   console.log(i) 
  }
  
  alert(i); // 10
Copy after login

对于有块级作用域的语言来说,比如java或是c#代码,i做为for初始化的变量,在for之外是访问不到的。因为i只存在于for循环体重,在运行完for循环后,for中的所有变量就被销毁了。而在javascript中则不是这样的,在for中的变量声明将会添加到当前的执行环境中(这里是全局执行环境),因此在for循环完后,变量i依旧存在于循环外部的执行环境。因此,会输出10。

2、声明变量

使用var声明变量时,这个变量将被自动添加到距离最近的可用环境中。对于函数内部,最接近的环境就是函数的局部变量。如果初始化变量时没有使用var,该变量会自动添加到全局函数中。

代码如下:

var name = "小明";
function getName(){
 alert( name ); //'undefined'
 var name = '小黄';
 alert(name ); //小黄
}
getName()
Copy after login

为什么第一个name是undefined呢。这是因为,javascript解析器,进入一个函数执行环境,先对var 和 function进行扫描。

相当于会把var或者function【函数声明】声明提升到执行环境顶部。

也就是说,进入我们的getName函数的时候,标识符查找机制查找到了var,查找的name是局部变量name,而不是全局的name,因为函数里面的name被提升到了顶部。

上面的代码会被解析成下面这样:

var name = "小明";
function getName(){
 var name;
 alert( name ); //'undefined'
 var name = '小黄';
 alert(name ); //小黄
}
getName()
Copy after login
 

延长作用域链:

  虽然执行环境只有两种——全局作用域和函数作用域,但是还是可以通过某种方式来延长作用域链。因为有些语句可以在作用域链的顶部增加一个临时的变量对象。
有两种情况会发生这种现象:
1、try-catch语句的catch块;
2、with语句;

以上就是本文的全部内容,希望对大家学习理解javascript执行环境及作用域有所帮助。

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template