gpt4 book ai didi

javascript - 使用模块模式时分配了多少内存?

转载 作者:行者123 更新时间:2023-11-29 10:50:21 24 4
gpt4 key购买 nike

我想将 Snippet 1 重构为 Snippet 2。考虑到大小,我认为这里的性能不是一个大问题,但我想了解关于此模块模式重构的内存使用情况.

模块模式确保我只从 DOM 中提取一次数据,这正是我想要的,而且它还形成了一个迷你注册表模式,因为数据是私有(private)的。

这两个片段都已经过测试并且基本上可以工作。

片段 1//用 SU 替换 SUniverisals

var SUniversals = function () {
// Pull from Server
this.universals.path = document.getElementById('universals').getAttribute('data-path');
this.universals.load = document.getElementById('universals').getAttribute('data-load');
// Set Manually
this.universals.debug = false;
};
SUniversals.prototype.universals = {};
SUniversals.prototype.get = function( key ) {
return this.universals[ key ];
};
SUniversals.prototype.set = function( key, value ) {
this.universals[ key ] = value;
};

片段 2

var SU = ( function () 
{
// private SU.get('load');
var universals = {};
universals.path = document.getElementById('universals').getAttribute('data-path');
universals.load = document.getElementById('universals').getAttribute('data-load');
universals.debug = false;
// pubulic
var publik = {};
publik.get = function( key )
{
return universals[ key ];
};
publik.set = function( key, value )
{
universals[ key ] = value;
};
return publik;
}());

最佳答案

几乎没有什么不同。片段 2 本质上是在创建一个单例。片段 1 可以看作是一个“类”。您可以创建“SUniversals”的多个实例/对象,并用它们做不同的事情。

实际上,片段 1 在内存方面效率更高。通过添加到对象的原型(prototype),无论您创建的对象数量如何,您基本上都只会拥有每个函数的 1 个副本。模块模式将创建单独的实体。

关于javascript - 使用模块模式时分配了多少内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11422602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com