gpt4 book ai didi

javascript - 揭示模块/原型(prototype)模式

转载 作者:搜寻专家 更新时间:2023-11-01 04:16:51 24 4
gpt4 key购买 nike

到目前为止,我使用 Revealing Module Pattern 来构建我的 Javascript,如下所示:

     var module = (function() {
var privateVar;

// @public
function publicFunction( ) {

}

return {
publicFunction: publicFunction
}
})();

Fiddle

虽然这段代码按预期工作,但我最近读到一篇文章说,如果您有多个实例,这种模式会使用大量内存,并且与其他模式相比,它存在一些速度问题。因为我喜欢使用这种模式,所以我搜索了没有所有这些“问题”的类似模式,然后我遇到了揭示原型(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
}
}();

Fiddle 2

我做错了什么?

最佳答案

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/

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