Kevin
Kevin

Reputation: 23634

Calling objects and array from revealing module pattern

var GlobalObject = (function(){

    var arr1 = [];
    var arr2 = [];
    var arr3 = [];
    var arr4 = []; 

        return {

         }

})();
  1. Now how would i call GlobalObject.arr1 across the application?
  2. Will it maintain its reference and value, when i do a push and pop.
  3. Will this cause any memory leak

Upvotes: 1

Views: 303

Answers (2)

stinkycheeseman
stinkycheeseman

Reputation: 45807

arr1 is defined only within the scope of the GlobalObject function. If you want to access it globally, you need to have the GlobalObject function return a reference to it. Read up on functional scope in javascript for a better understanding of this. Currently your function returns an empty object. You want to do something like this:

...
return {
   "array1": arr1,
   "array2": arr2,
   "array3": arr3,
   "array4": arr4
};

(though you can maintain the privacy of those arrays by not returning them)

The GlobalObject will maintain arr1's reference and value until you manually de-reference it (setting it to null). Javascript's garbage collector only deletes objects that aren't needed anymore.

Your current code shows no memory leaks. Watch out for circular references and closures.

Upvotes: 2

Pointy
Pointy

Reputation: 413996

  1. You can't unless arr1 is exposed as a value of a property of the returned object
  2. Yes
  3. That depends on the rest of your code

For (1), you'd have to make sure that one of the properties of the object returned is a reference to the array:

    // ...
    return {
      whatever: arr1,
      // ...
    };

As to memory leaks, there's nothing about a setup like this that's particularly problematic.

Upvotes: 1

Related Questions