- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
到目前为止,我使用 Revealing Module Pattern 来构建我的 Javascript,如下所示:
var module = (function() {
var privateVar;
// @public
function publicFunction( ) {
}
return {
publicFunction: publicFunction
}
})();
虽然这段代码按预期工作,但我最近读到一篇文章说,如果您有多个实例,这种模式会使用大量内存,并且与其他模式相比,它存在一些速度问题。因为我喜欢使用这种模式,所以我搜索了没有所有这些“问题”的类似模式,然后我遇到了揭示原型(prototype)模式。据我所知,JavaScript 的 Prototype 有更好的内存管理。
现在我想知道使用揭示原型(prototype)模式对内存是否更快/更好? This benchmark让我感到惊讶,因为模块模式似乎要快得多。有什么理由吗?
此外,我无法弄清楚如何使用 Revealing Prototype Pattern 拥有多个实例(与上面的 Revealing Module Pattern Fiddle 相比):
var prototypeModule = function( el ) {
this.init( );
};
prototypeModule.prototype = function () {
var privateVar;
// @public
function init( ) {
}
return {
init: init
}
}();
我做错了什么?
最佳答案
Although this code works as expected I red an article lately that this pattern uses large amount of memory if you have multiple instances
您在第一个片段中呈现的代码是一个单例模块,没有“多个实例”。完全没问题。
只有您在 fiddle 中标题为 Module pattern - Multiple instances
的东西才会受到 memory disadvantages 的影响。当它实例化大量对象时。但是,请注意,这不是“模块模式”,而是“工厂模式”。
Now I'm wondering if it's faster / better for memory to use the Revealing Prototype Pattern?
一般来说,如果应用正确,是的。
This benchmark surprised me, because the Module Pattern seems to be much faster. Is there any reason?
他们模块的代码一团糟,无法修复。我什至不想对那里发生的事情发表评论。
Also I couldn't figure out how to have multiple instances with the Revealing Prototype Pattern
原型(prototype)的好处是它的属性在所有实例之间共享。这意味着所有实例的 .init
方法都指向同一个函数,该函数在其揭示的模块范围内有一个 privateVar
- 这个变量对所有实例只存在一次!它是静态的,而不是特定于实例的。
如果要使用原型(prototype),就不能访问真正私有(private)的变量;您将需要使用公共(public)属性。但是,您的 clickFunction
无论如何都需要一个本地(私有(private))变量来关闭它,因此不使用此处的原型(prototype)也没有错:
function Constructor( el ) {
var privateVar = $( el );
privateVar.on( 'click', function clickFunction() {
privateVar.addClass('click');
});
console.log( 'constructor: ' + privateVar.attr('id') );
}
关于javascript - 揭示模块/原型(prototype)模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24488196/
我有一个交互网络,我使用以下代码制作邻接矩阵,随后计算网络节点之间的相异性,然后将它们聚类以形成模块: ADJ1=abs(adjacent-mat)^6 dissADJ1% as.dist %
对这些东西仍然很陌生,所以我希望我对问题的描述是准确的。 我刚刚插入 Zurb Reveal,并使用 在页面加载时使其正常工作 $(document).ready(function (){ $
我正在对分类数据进行聚类分析,因此使用 k-modes 方法。 我的数据被塑造成一个偏好调查: 你喜欢头发和眼睛吗? 受访者可以从固定(多项选择)的 4 种可能性中选出一个答案。 因此,我得到了假人,
我正在尝试了解(Revealing) Module Pattern 中的public` 属性 是如何工作的。 Carl Danley "The Revealing Module Pattern"指出的
Python 中有一个非常方便的函数:repr()当应用于包含空白字符的字符串时,将打印出该字符串的表示,不会导致对字符串实际内容的任何人为误解。 例如: $ python -c "print rep
我已经安装了 Foundation 6,到目前为止一切似乎都工作正常。现在我想添加一个显示模式。添加了 jQuery v2.2.4 并加载了必要的库,如下所示: FOUNDATION_VERSION
我是一名优秀的程序员,十分优秀!