Using the Module Pattern for larger projects

谁都会走 提交于 2019-12-05 10:31:49

问题


I'm interested in using the Module Pattern to better organize my future projects. Unfortunately, there are only a few brief tutorials and proof-of-concept examples of the Module Pattern.

Using the module pattern, I would like to organize projects into this sort of structure:

project.arm.object.method();

Where "project" is my global project name, "arm" is a sub-section or branch of the project, "object" is an individual object, and so on to the methods and properties.

However, I'm not sure how I should be declaring and organizing multiple "arms" and "objects" under "project".

var project = window.project || {};
project.arm = project.arm || {};

project.arm.object = (function() {

    var privateVar = "Private contents.";

    function privateMethod() {
        alert(privateVar);
    }

    return {
        method: privateMethod
    };

}());

Are there any best practices or conventions when defining a complex module structure? Should I just declare a new arm/object underneath the last?


回答1:


Here's a good write-up on what you're after; http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth




回答2:


Dojo's dojo.declare is great for this kind of thing since it

Create a constructor using a compact notation for inheritance and prototype extension.

It's also really convenient if even for just removing this kind of boiler plate:

var project = window.project || {};
project.arm = project.arm || {};

If you just want that feature, then you could use dojo.setObject, but of course, writing something to do the same is trivial.

dojo.setObject("project.arm.object" (function() {
    var privateVar = "Private contents.";

    function privateMethod() {
        alert(privateVar);
    }

    return {
        method: privateMethod
    };
}()));

I recently used dojo.declare/dojo.setObject for a large JavaScript project (86 files, 7K+ lines (not counting comments and blank lines)), and it was a breeze to keep everything organized and manageable, especially when you have an inclusion mechanism like dojo.require and dojo.provide.




回答3:


There are a lot of nuances to how people prefer to do that, but the main benefit of what you're calling the module pattern (a named scope), is that your not cluttering up the global namespace, which helps keep things clean if you bring in other libraries etc, and avoids name collisions.

How you organize the names and nested scopes within that is largely a matter of personal preference.



来源:https://stackoverflow.com/questions/2718172/using-the-module-pattern-for-larger-projects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!