Can storing large variables in a closure cause problems?
closures, javascript
Solution
not sure what you are trying to achieve, this should provide you with some private storage on different levels:
var privateStorage = function () {
// only 1 copy total
var bigJsonData = {...}
return function() {
// 1 copy for each instance
var instanceData = {...}
return function() {
// something to do many times per instance
return something_useful
}
}
}(); // returns function that privatelly knows about bigJsonData
var a = privateStorage(); // a is now 1st instance of the inner-most function
var b = privateStorage(); // a and b share the SAME bigJsonData object, but use different instanceData objects
a1 = a();
a2 = a();
Problem
I have a function in which I'm using closure as follows: ``` function myobject() { var width=300, height=400, bigjsondata = { } // assume this is a big variable ~ 300k function obj(htmlelement) { // plot a graph in this htmlelement based on bigjsondata } return obj; } var plot1 = myobject(); plot1('#holder1'); var plot2 = myobject(); plot1('#holder2'); ``` the variable `bigjsondata` contains a large dataset. The question is: does it allocate memory for `bigjsondata` whenever I create a variable `var a = myobject()` ? Can it lead to memory problems if a lot of instances are created? If so what is the best way to load it only once? (`bigjsondata` does not change) Edit: At the end I would like `myobject` to be globally accessible.