Accessing variables from other functions without using global variables Accessing variables from other functions without using global variables javascript javascript

Accessing variables from other functions without using global variables


I think your best bet here may be to define a single global-scoped variable, and dumping your variables there:

var MyApp = {}; // Globally scoped objectfunction foo(){    MyApp.color = 'green';}function bar(){    alert(MyApp.color); // Alerts 'green'} 

No one should yell at you for doing something like the above.


To make a variable calculated in function A visible in function B, you have three choices:

  • make it a global,
  • make it an object property, or
  • pass it as a parameter when calling B from A.

If your program is fairly small then globals are not so bad. Otherwise I would consider using the third method:

function A(){    var rand_num = calculate_random_number();    B(rand_num);}function B(r){    use_rand_num(r);}


Consider using namespaces:

(function() {    var local_var = 'foo';    global_var = 'bar'; // this.global_var and window.global_var also work    function local_function() {}    global_function = function() {};})();

Both local_function and global_function have access to all local and global variables.

Edit: Another common pattern:

var ns = (function() {    // local stuff    function foo() {}    function bar() {}    function baz() {} // this one stays invisible    // stuff visible in namespace object    return {        foo : foo,        bar : bar    };})();

The returned properties can now be accessed via the namespace object, e.g. ns.foo, while still retaining access to local definitions.