向JavaScript模块模式添加方法

向JavaScript模块模式添加方法

本文介绍了向JavaScript模块模式添加方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚了解了JavaScript模块模式.喜欢它!

Just learned about JavaScript module pattern. Love it!

因此,我创建了我的通用自定义库,该库位于我包含在所有项目中的一个文件中.然后,我想为每个单独的项目添加几个特定于项目的方法,并将它们放在单独的文件中.我不想为这些方法创建一个全新的对象,而是将它们添加到现有的MODULE对象中.

So, I created my generic custom library which is located in one file which I include on all my projects. I then want to add a couple project specific methods for each individual project, and would like to put them in a separate file. Instead of creating a whole new object for these methods, I would like to add them to my existing MODULE object.

我该怎么做?谢谢

var MODULE = (function () {
    var my = {},
        privateVariable = 1;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
    };

    return my;
}());

推荐答案

您可以通过说Module.namedproperty = ...whatever...

但是应该注意,如果它在另一个文件中,则将无法访问模块状态下的任何私有变量.

But it should be noted that if this is in a different file it won't have access to any private variables in the module state.

如果您希望这些新方法具有其他私有状态,或者不担心先运行哪个文件,可以按以下方式设置模块

If you want to have additional private state for these new methods, or want to not worry about which file is run first you can set up your modules like this

var MODULE = (function (my) {
    var privateVariable = 1;

    function privateMethod() {
        // ...
    }

    my.moduleProperty = 1;
    my.moduleMethod = function () {
        // ...
    };

    return my;
}(MODULE||{}));

如果尚未创建该模块,则将创建一个新模块;如果已创建,则将其添加到现有模块中.

Which will create a new module if the module hasn't been created yet, or add to the existing one if it has.

尽管如此,私有变量仍将对它们自己的特定闭包是私有的,而不是整个命名空间/模块的私有.

The private variables will still be private to their own particular closure though, and not to the namespace/module as a whole.

此模块格式将输入输入到其闭包函数中.如果已经定义了MODULE,则它将接受MODULE对象,否则将创建一个新的空对象. ||是逻辑或",因此MODULE||{}与如果定义了MODULE并且为真(将像MODULE这样的对象将为真),则将其传递,如果未定义或否则为假,则传递一个空对象.

This module format takes in an input into its closure function. If MODULE is already defined, it takes in the MODULE object, otherwise it creates a new empty object. || is logical OR, so MODULE||{} is the same as "if MODULE is defined and is truthy (which an object like MODULE will be), then pass it, if it is undefined or otherwise falsy, pass an empty object.

多余的括号不是严格必需的,但是它们是一种约定,可以清楚地表明要传递函数的结果,而不是函数本身.

The extra parentheses are not strictly necessary, but they're a convention to make it clear that the result of the function is being passed, not the function itself.

这篇关于向JavaScript模块模式添加方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 23:58