elevance
elevance

Reputation: 43

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"
});

Upvotes: 4

Views: 1096

Answers (4)

JaredPar
JaredPar

Reputation: 755567

No this will not work because the variable c is defined within the function and is not available outside of the function. One option though is to pass the variable c into the function provided to a

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

a(function(c) { 
  alert(c);  //at this point, c should = "test" 
}); 

Upvotes: 2

meder omuraliev
meder omuraliev

Reputation: 186762

As others have said, this isn't possible. You can

1. Declare the c variable outside of the scope of the function

2. Pass an argument to f:

function a(f) { var c = { name: 'test' }; f(c)  };
a(function(o) { alert(o.name) })

Upvotes: 0

cdhowie
cdhowie

Reputation: 169478

No, this is not possible. The scope you declare your anonymous function in does not have access to this c variable -- in fact, nothing but a will ever has access to c.

Upvotes: 2

Pointy
Pointy

Reputation: 414036

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"

Upvotes: 4

Related Questions