Accessing internal variables from external functions in javascript

Is it possible to access an internal variable from an external function such as this example?

function a(f) { var c = 'test'; f(); } a(function() { alert(c); //at this point, c should = "test" }); 
+4
source share
4 answers

No, that will not work. What matters is where the (lexically) function is defined , and not where it is called.

When determining what (if something) means "c", the language looks in the local area, and then in the next area based on the definition of the function. Thus, if this call to "a" took place in another function that had its own local "c", then this value would be what the warning showed.

 function b() { var c = 'banana'; a(function() { alert(c); }); } b(); // alert will show "banana" 
+4
source

No, It is Immpossible. The area in which you declare your anonymous function does not have access to this variable c - in fact, nothing but a will ever have access to c .

+2
source

No, this will not work, because the variable c defined inside the function and is not available outside the function. One option is to pass the variable c to the function provided by a

 function a(f) { var c = 'test'; f(c); } a(function(c) { alert(c); //at this point, c should = "test" }); 
+2
source

As others have said, this is not possible. You can

1. Declare a variable c outside the scope

2. Pass the argument f :

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

All Articles