Kayote
Kayote

Reputation: 15627

Understanding Scope

I thought I understood scope however, while thinking of a particular code problem I had, I am confused by the following:

var a = {
  aFunc: function() {
    console.log(x);
  }
};
var b = {
  bFunc: function() {
    var x = c.x;
    console.log(x);
    a.aFunc();
  }
};
var c = {
  x: 'x is in c'
};

b.bFunc();

Question: aFunc is called inside bFunc, why do I get 'x is not defined' inside aFunc? Isn't this a simple closure where a.aFunc can access b.bFunc scope?

Upvotes: 3

Views: 45

Answers (2)

discy
discy

Reputation: 430

No, every function has it's own scope. A function call doesn't share it's scope with it. If you want to share variables via scope you have to put them in the shared scope like this:

var x = 'x from shared scope';
var a = {
  aFunc: function() {
    console.log('aFunc: ' + x);
  }
};
var b = {
  bFunc: function() {
    var x = 'x only in scope b';
    console.log('bFunc: '+ x);
    a.aFunc(); 
  }
};

b.bFunc();

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 239473

Isnt this a simple closure where a.aFunc can access b.bFunc scope?

No. Closure is a property of the functions which encloses over all the variables in their scope, during their definition, not during their invocation.

In your case, when a.aFunc is called, it doesn't enclose the variables in b.bFunc because, it is just invoked there, not defined there.


Let's try to understand this, with this example

function Test1(func) {
  var a = 0;
  func();
}

function Test() {
  var a = 5;
  Test1(function() {
    console.log(a);
  });
}

Test();

will print 5, because when func() is executed, the actual function object has enclosed over the variables in Test, since the closure happens during the function definition.

Upvotes: 2

Related Questions