Execution environment and scope, variable object, scope chain, closure

一:Execution environment and scope and variable objects

  var color = "blue";   function changeColor(){     var anotherColor = "red";     // 这里可以访问color和anotherColor   }   // 这里只能访问color   changeColor();

执行环境是javascript中最为重要的一个概念。每个执行环境都有一个与之关联的变量对象(保存执行环境中所有定义的变量和函数)。
二:
scope chain
  1. When code is executed in an execution environment, a scope chain is created. A scope chain is essentially a list of pointers to variable objects.

  2. If the execution environment is a function, its active object (which initially contains only one variable->argument object) is used as the variable object. The ps:argument object does not exist in the global environment.

  3. (Based on 2 conditions) The next variable object in the scope chain is from the outer environment, and the next variable object is from the next outer environment. In this way, it continues to the global execution environment; the variable object of the global execution environment is always the last object in the scope chain.

 
Three: js
has no block-level scope
  if (true) {
        var color = "blue"; } alert(color); //"blue" 注:在jsif语句中的变量申明会将变量添加到if外部的执行环境中(当前是指window变量);此时window变量对象中有一个值是 color = 'blue'

    for (var i=0; i < 10; i++){
            doSomething(i);
    }
    alert(i);      //10 注:在jsfor循环结束后依然会存在循环外部的执行环境中,即window变量对象有 i = 10
四:
Closure

  A closure is a function that has access to a variable in the scope of another function. A common way to create a closure is to create a function inside another function.

eg: function createComparisonFunction(propertyName) {
        return function(object1, object2){ var value1 = object1[propertyName]; var value2 = object2[propertyName]; if (value1 < value2){ return -1; } else if (value1 > value2){ return 1; } else { return 0; } }; } //创建函数 var compareNames = createComparisonFunction("name"); //调用函数 var result = compareNames({ name: "Nicholas" }, { name: "Greg" }); 注:createComparisonFunction()函数返回后,其执行环境的作用域链会被销毁,但它的活动对象仍然会留在内存中,匿名函数的作用域链仍然在引用这个活动对象
以上是作用域链的这种配置机制引出了一个副作用,即闭包只能获取外部函数任何变量的最后一个值
function createFunctions(){
    var result = new Array(); for (var i=0; i < 10; i++){ result[i] = function(){ return i; }; } console.log(i) // i = 10 for (var j = 0; j < 10; j++){ console.log(result[j]()); // 打印10个10 } return result; } createFunctions(); 修改: function createFunctions(){ var result = new Array(); for (var i = 0; i < 10; i++){ result[i] = function(num){ return num; }(i); } console.log(result); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] return result; } createFunctions();
 -----借鉴于javascript高级程序设计,有不足之处,欢迎指点

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324691954&siteId=291194637