带有命名空间的Javascript模块模式

时间:2015-08-27 14:23:54

标签: javascript namespaces module-pattern code-standards

我一直在使用具有正确名称间距的JavaScript模块模式。所以基本上我声明了名称空间,每个名称空间都有一些封装在其中的模块。这是我到目前为止所写的内容。代码已被正确评论。

// namespace has been defined somewhere not to worry that it will be undefined
if (NAMESPACE == null || typeof (NAMESPACE) == 'undefined') {
    NAMESPACE = {};

    var id = function (id) {
        var _all_ids = {};
        var persona = {};
        var _id = id; // _id is a local variable that stores the argument

        var getId = function () { //this function returns the local private variable
            return _id;
        }

        persona.getId = getId;
        var _closed = false;

        var close = function () {
            delete _all_ids[getId()];
            this._closed = true;
        }

        persona.close = close;

        return persona; // persona is an object that has two properties `getId` and `close`. Both these are functiona
    }

    NAMESPACE['id'] = id; // so basically this will become NAMESPACE.id.getId or NAMESPACE.id.close
} 

我已经完全评论了tis代码,任何人都可以理解。它声明了一个简单的命名空间,然后在其中添加一个模块。该模块当然是使用封装。

我的一位教师建议此代码有一个基本的缺陷标准或其他。虽然代码运行良好,但我无法解决这个问题。

标准明智吗?或者我完全错了吗?

4 个答案:

答案 0 :(得分:1)

我已经扩展了一些示例来展示原则。

// NAMESPACE with install/define method, like when using require.js
var NAMESPACE = (function ( doc, win ) {
    var _modules = {};
    return {
        'install' : function ( name, definition ) {
            if (!_modules.hasOwnProperty(name)) {
                _modules[name] = definition;
                this[name] = _modules[name];
            }
            else throw new Error('Module ' + name + ' is already installed.');
        }
    };
}( document, window ));
// Your actual module to use in the NAMESPACE
NAMESPACE.install('id', (function ( id ) {
    var _all_ids = {}, 
        _id = id, 
        _closed = false; 
    return { 
        'getID' : function () { 
            return _id; 
        }, 
        'close' : function () { 
            delete _all_ids[_id];
            _closed = true; 
        } 
    }; 
}( 'someDefaultID' )));

// NAMESPACE as an object we pass around
var NAMESPACE = {};
(function ( NAMESPACE ) {
    var id,
        NAMESPACE = NAMESPACE;
    if (NAMESPACE == null || typeof (NAMESPACE) == 'undefined') {
        NAMESPACE = {};
        window.NAMESPACE = NAMESPACE;
    }
    id = (function ( id ) {
        var _all_ids = {}, 
            _id = id, 
            _closed = false; 
        return { 
            'getID' : function () { 
                return _id; 
            }, 
            'close' : function () { 
                delete _all_ids[_id];
                _closed = true; 
            } 
        }; 
    }( 'someDefaultID' ));
    NAMESPACE['id'] = id;
}( window.NAMESPACE ))

答案 1 :(得分:0)

为什么不将函数放在命名空间中?

NAMESPACE = {
 id: function (id) {
  // The id function in here
 }
}

答案 2 :(得分:0)

命名空间的目的是避免污染全局范围。在您的代码中,

if (NAMESPACE == null || typeof (NAMESPACE) == 'undefined') {
    NAMESPACE = {};

    var id = function (id) {
        // ...
    }

    NAMESPACE['id'] = id; // so basically this will become NAMESPACE.id.getId or NAMESPACE.id.close
}

id现在在全局范围和命名空间中定义。这违背了使用命名空间的目的。

实现定义命名空间而不污染全局范围的相同目标的简单JS方法是重新排列

if (NAMESPACE == null || typeof (NAMESPACE) == 'undefined') {
    NAMESPACE = {};

    NAMESPACE['id'] = function (id) {
        // ...
    }
}

if (NAMESPACE == null || typeof (NAMESPACE) == 'undefined') {
    NAMESPACE = {
        id: function (id) {
        // ...
    }

}

正如@Lekoaf建议的那样。

然而,避免全球污染的现代方法是简单地将所有代码包含在IIFE中。虽然有不止一种方法将您的代码封装在IIFE中,但最简单的方法是将其放入原来的

(function(){ // Beginning of IIFE
if (NAMESPACE == null || typeof (NAMESPACE) == 'undefined') {
    NAMESPACE = {};

    var id = function (id) {
        var _all_ids = {};
        var persona = {};
        var _id = id; // _id is a local variable that stores the argument

        var getId = function () { //this function returns the local private variable
            return _id;
        }

        persona.getId = getId;
        var _closed = false;

        var close = function () {
            delete _all_ids[getId()];
            this._closed = true;
        }

        persona.close = close;

        return persona; // persona is an object that has two properties `getId` and `close`. Both these are functiona
    }

    NAMESPACE['id'] = id; // so basically this will become NAMESPACE.id.getId or NAMESPACE.id.close
} 
})(); // End of IIFE

答案 3 :(得分:0)

您可以使用扩充模块模式,以避免覆盖全局模块及其方法。

//fooModule does not exist, so it is defined as an empty object
var fooModule = (function(app, name, definition) {
    if (!app[name]) app[name] = definition;
    else throw new Error("this method has already been defined");
    return app;
})(fooModule || {}, "foobar", function() {
    console.log("foobar");
});

//fooModule now exists, so we use the pre-existing object instead of an empty one
var fooModule = (function(app, name, defintion) {
    if (!app[name]) app[namepace] = definition;
    else throw new Error("this method has already been defined");
    return app;
})(fooModule || {}, "barfoo", function() {
    console.log("barfoo");
});

//throws an error because barfoo has already been set to fooModule
var fooModule = (function(app, name, defintion) {
    if (!app[name]) app[namepace] = definition;
    else throw new Error("this method has already been defined");
    return app;
})(fooModule || {}, "barfoo", function() {
    console.log("should throw error");
});

fooModule.foobar(); //"foobar"
fooModule.barfoo(); //"barfoo"    

重要的部分是myModule || {}。如果模块存在,请使用它,如果它没有,则创建模块。

这仅解决全局对象上的方法。你看过this article了吗?我可能读过最好的模块模式。