I was wondering if there is any way to access variables trapped by closure in a function from outside the function; e.g. if I have:
A = function(b) { var c = function() {//some code using b}; foo: function() { //do things with c; } }
is there any way to get access to c
in an instance of A
. Something like:
var a_inst = new A(123); var my_c = somejavascriptmagic(a_inst);
A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function's variables — a scope chain. The closure has three scope chains: it has access to its own scope — variables defined between its curly brackets. it has access to the outer function's variables.
No, You can't access let variables outside the block, if you really want to access, declare it outside, which is common scope.
Disadvantages of closures There are two main disadvantages of overusing closures: The variables declared inside a closure are not garbage collected. Too many closures can slow down your application. This is actually caused by duplication of code in the memory.
Webpack, Babel, UglifyJS, and TypeScript are the most popular alternatives and competitors to Closure Compiler.
A simple eval inside the closure scope can still access all the variables:
function Auth(username) { var password = "trustno1"; this.getUsername = function() { return username } this.eval = function(name) { return eval(name) } } auth = new Auth("Mulder") auth.eval("username") // will print "Mulder" auth.eval("password") // will print "trustno1"
But you cannot directly overwrite a method, which is accessing closure scope (like getUsername()), you need a simple eval-trick also:
auth.eval("this.getUsername = " + function() { return "Hacked " + username; }.toSource()); auth.getUsername(); // will print "Hacked Mulder"
Variables within a closure aren't directly accessible from the outside by any means. However, closures within that closure that have the variable in scope can access them, and if you make those closures accessible from the outside, it's almost as good.
Here's an example:
var A = function(b) { var c = b + 100; this.access_c = function(value) { // Function sets c if value is provided, but only returns c if no value // is provided if(arguments.length > 0) c = value; return c; }; this.twain = function() { return 2 * c; }; }; var a_inst = new A(123); var my_c = a_inst.access_c(); // my_c now contains 223 var my_2c = a_inst.twain(); // my_2c contains 446 a_inst.access_c(5); // c in closure is now equal to 5 var newer_2c = a_inst.twain(); // newer_2c contains 10
Hopefully that's slightly useful to you...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With