Ian Warburton
Ian Warburton

Reputation: 15676

Does this use the scope chain?

var a = 1;

function hello() {
   (function(){
      alert(a);
   }());
}

Or is the scope chain only used when objects have been chained together using the prototype property?

Upvotes: 1

Views: 85

Answers (2)

Alex Char
Alex Char

Reputation: 33218

I'm not sure if I understand right your question but I will try to answer. You declare a variable in global scope a. After you have a function declaration and an IIFE as closure in hello. When you call hello the IIFE will execute and because in local scope there isn't any variable a will go up one level to global scope. So alert 1.

var a = 1;

function hello() {
  (function() {
    alert(a);
  }());
}

hello();//alerts 1

In the next example I declare a local variable a so alert will be 3.

    var a = 1;

    function hello() {
      var a = 3;
      (function() {
        alert(a);
      }());
    }

    hello(); //alerts 3

Upvotes: 4

potatopeelings
potatopeelings

Reputation: 41065

Yes the scope chain is used. The scope chain is more related to closures.

When hello is called, for getting the value of a for alert(a), the inner anonymous function is searched for the variable a.

Not finding anything, it moves up to the function hello and then one level up to the function / global scope in which hello is defined.

Upvotes: 4

Related Questions