最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

If the "with" statement in Javascript creates a new scope, why does this closure doesn't contain the n

programmeradmin0浏览0评论

If the with statement in Javascript creates a new scope, shouldn't clicking on the links show a different x which are in different scopes? It doesn't.

<a href="#" id="link1">ha link 1</a>
<a href="#" id="link2">ha link 2</a>
<a href="#" id="link3">ha link 3</a>
<a href="#" id="link4">ha link 4</a>
<a href="#" id="link5">ha link 5</a>


<script type="text/javascript">

    for (i = 1; i <= 5; i++) {

        with({foo:"bar"}) {
            var x = i;
            document.getElementById('link' + i).onclick = function() { alert(x); return false; }
        }

    }

</script>

If the with statement in Javascript creates a new scope, shouldn't clicking on the links show a different x which are in different scopes? It doesn't.

<a href="#" id="link1">ha link 1</a>
<a href="#" id="link2">ha link 2</a>
<a href="#" id="link3">ha link 3</a>
<a href="#" id="link4">ha link 4</a>
<a href="#" id="link5">ha link 5</a>


<script type="text/javascript">

    for (i = 1; i <= 5; i++) {

        with({foo:"bar"}) {
            var x = i;
            document.getElementById('link' + i).onclick = function() { alert(x); return false; }
        }

    }

</script>
Share Improve this question edited Aug 6, 2017 at 14:13 Cœur 38.7k26 gold badges202 silver badges277 bronze badges asked Apr 30, 2010 at 7:00 nonopolaritynonopolarity 151k142 gold badges489 silver badges781 bronze badges 1
  • 1 with is not one of the good parts for a reason. – Sky Sanders Commented Apr 30, 2010 at 7:50
Add a comment  | 

1 Answer 1

Reset to default 27

The with statement doesn't creates a full new lexical scope, it just introduces an object in front of the scope chain, for example, if you capture the i variable, it will work:

for (var i = 1; i <= 5; i++) {
  with({x:i}) {
    document.getElementById('link' + i).onclick = function() {
      alert(x);
      return false;
    };
  }
}

Let me try to explain it better with another example:

var x = 10, y = 10;   // Step 1

with ({x: 20}) {      // Step 2

  var x = 30, y = 30; // Step 3

  alert(x); // 30
  alert(y); // 30
}

alert(x); // 10
alert(y); // 30

In the Step 1, the x and y variables are declared and they are part of the first object in the scope chain, the global object.

In the Step 2, a new object ({x:20}) is introduced into the scope chain by the with statement, now the scope chain looks something like this:

   ________              ________
  | x = 10 | <--------- | x = 20 |
  | y = 10 |             ¯¯¯¯¯¯¯¯¯
   ¯¯¯¯¯¯¯¯ 

In the Step 3, another var statement is executed, but it has no effect because as I said before, only functions create a full lexical scope.

The var statement has no effect, but the assignment has, so when the x variable is resolved, is reached on the first object on the scope chain, the one we introduced using with.

The y identifier is resolved also, but it is not found on the first object in the chain, so the lookup continues up, and finds it on the last object, the scope chain after the assignments looks like this:

   ________              ________
  | x = 10 | <--------- | x = 30 |
  | y = 30 |             ¯¯¯¯¯¯¯¯¯
   ¯¯¯¯¯¯¯¯ 

When the with statement ends, the scope chain is finally restored:

   ________ 
  | x = 10 |
  | y = 30 |
   ¯¯¯¯¯¯¯¯ 

Edit: Let me expand a little bit and talk about functions.

When a function is created its current parent scope is bound, for example:

var fn;
// augment scope chain
with ({foo: "bar"}) {
  fn = function () { // create function
    return foo;
  };
}​​
// restored scope chain
fn(); // "bar", foo is still accessible inside fn

A new lexical scope is created and added to the scope chain when the function is executed.

Basically all identifiers (names) of function arguments, variables declared with var and functions declared with the function statement, are bound as properties of a new object created behind the scenes, just before the function itself executes (when controls enters this new execution context).

This object is not accessible through code, is called the Variable Object, for example:

var x = 10, y = 10;   // Step 1

(function () {        // Step 2
  var x, y; 

  x = 30;             // Step 4
  y = 30; 

  alert(x); // 30
  alert(y); // 30
})();                 // Step 3

alert(x); // 10       // Step 5
alert(y); // 10

In the Step 1, again as in my first example, the x and y variables are declared and they are part of the first object in the scope chain, the global object.

In the Step 2, a new function object is created, the parent scope is stored in this moment, into the [[Scope]] of that function, containing now x and y.

In the Step 3, the function is invoked, starting the Variable Instantiation process, which creates a new object in the scope chain, containing the locally scoped x and y variables declared inside this new function, the scope chain at this moment looks like this:

  parent scope           Variable Object
   ________              _______________
  | x = 10 | <--------- | x = undefined |
  | y = 10 |            | y = undefined | 
   ¯¯¯¯¯¯¯¯              ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯ 

Then in the Step 4, the assignment of x and y is done, but since the new lexical scope has been created, it doesn't affect the outer values.

  parent scope           Variable Object
   ________              ________
  | x = 10 | <--------- | x = 30 |
  | y = 10 |            | y = 30 | 
   ¯¯¯¯¯¯¯¯              ¯¯¯¯¯¯¯¯ 

And finally, in the Step 5, the function ends and the scope chain is restored to its original state.

   ________ 
  | x = 10 |
  | y = 10 |
   ¯¯¯¯¯¯¯¯ 

Recommended lectures:

  • ECMA-262-3 in detail. Chapter 4: Scope chain
  • Scope Chain and Identifier Resolution

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论