Nas*_*sir 6 javascript closures
我有一个函数,我在其中使用闭包如下:
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');
Run Code Online (Sandbox Code Playgroud)
该变量bigjsondata包含一个大型数据集.问题是:bigjsondata每当我创建变量时它是否分配内存var a = myobject()?
如果创建了很多实例,它会导致内存问题吗?
如果是这样,只加载一次的最佳方法是什么?(bigjsondata不改变)
编辑:最后我想myobject全球访问.
不确定您想要实现什么,这应该为您提供不同级别的一些私人存储:
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
135 次 |
| 最近记录: |