0

Is there any way to access scoped variables from outside the scope?

For example how to edit count from outside of this function:

var counter = (function(){
    var count = 0;
    return function () {
        return ++count;
    };
})();
qwertynl
  • 3,912
  • 1
  • 21
  • 43

1 Answers1

4

It is not currently possible (nor do I think it will ever be possible) to access a local variable from outside the scope.

That is the whole idea.

What you can do is change the return of the function to return an object so that you can increase and decrease the count variable:

function counterObject = (function(){
    var count = 0;
    return {
       up: function(){ return ++count; },    
       down: function(){ return --count; }      
    };
})();

counterObject.up(); // 1
counterObject.up(); // 2
counterObject.up(); // 3
counterObject.down(); // 2
counterObject.up(); // 3

But aside from doing the above there is no real access to the local scoped variable.

qwertynl
  • 3,912
  • 1
  • 21
  • 43
  • `__parent__` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Parent – Benjamin Gruenbaum Dec 30 '13 at 19:55
  • If you're going to do something like this it should be a community wiki, not a simple Q/A because you are not and never will be the sole authority on something like this, and your answer will need to be molded into perfection by the community. –  Dec 30 '13 at 20:05
  • 1
    You **are** allowed to answer your own question on the Stack Exchange. I am not claiming any authority. – qwertynl Dec 30 '13 at 20:06
  • 2
    @JHa I'm not an expert on the subject matter of this specific Q&A, but [answering your own question](http://stackoverflow.com/help/self-answer) is allowed, and even encouraged, here. – Josh Darnell Dec 30 '13 at 20:18
  • What you've done here is implement the Module pattern as described http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript This allows the usage of public and private members of objects and encapsulation in Javascript. – Jason Dec 31 '13 at 01:23