Kayote Kayote - 6 months ago 13
Javascript Question

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?

Answer

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.