1
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
8
  • What do you mean by memory leak? Commented Jan 24, 2013 at 15:14
  • @Bergi: Will it pollute my namespace by creating new objects. Commented Jan 24, 2013 at 15:16
  • currently, your namespace is empty. And of course this code creates a few objects, but that's its purpose, isn't it? Commented Jan 24, 2013 at 15:18
  • @Bergi: Will it get garbage collected automatically since its in closure. Commented Jan 24, 2013 at 15:19
  • As it stands, yes. It won't if you export any functions that have access to the variables. Commented Jan 24, 2013 at 15:20

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Circular references are only dangerous if they include DOM elements.
1
  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.

2 Comments

Can you show mt the code for point 1 and for your third question... if i calling a function which is in another class[revealing module pattern]... will that cause problem in terms of leaks.
@Kevin answer updated. The memory leak question is completely dependent on other code; there's nothing special about objects created this way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.