Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access inner variables from external functions in javascript

Is it possible to access an inner variable from an external function like this example?

function a(f) {
  var c = 'test';
  f();
}

a(function() {
  alert(c);  //at this point, c should = "test"
});
like image 221
elevance Avatar asked Feb 25 '23 18:02

elevance


1 Answers

No, that won't work. What matters is where (lexically) a function is defined, not where it's invoked.

When figuring out what (if anything) "c" refers to, the language looks in the local scope, then in the next scope out based on the definition of the function. Thus if that invocation of "a" took place in another function that did have its own local "c", then that value would be what the alert showed.

function b() {
  var c = 'banana';
  a(function() {
    alert(c);  
  });
}

b(); // alert will show "banana"
like image 50
Pointy Avatar answered Feb 28 '23 08:02

Pointy