【问题标题】:Javascript Define Module Method AssignmentJavascript 定义模块方法分配
【发布时间】:2012-12-02 18:34:37
【问题描述】:

我正在尝试将定义模块方法添加到我的顶级命名空间,它首先定义命名空间。例如,

APP.define('modules.moduleName', function () { 
    return {name: 'Module 1' }; 
});

但似乎在我的实现中,存在分配问题。这是我的实现的简化示例。

var APP = APP || {};
APP.namespace = function( nsString ) {

    var parts  = nsString.split('.'),
        parent = this,
        i;

    if (parts[0] === 'APP') {
        parts = parts.slice(1);
    }

    for ( i = 0; i < parts.length; i++ ) {
        if (typeof parent[parts[i]] === 'undefined') {
            parent[parts[i]] = {};
        }
        parent = parent[parts[i]];
    }

    return parent;
};

// Simplified example of my define function
APP.define = function( name, definition ) {
    var namespace = APP.namespace( name );

    namespace     = definition();
    return namespace;
};

// Example Module
APP.define('modules.example', function () {

    return {
        name   : 'Application',
        module : 'APP.module'
    };
});

但是,在将命名空间分配给definition() 后,似乎命名空间未分配在 APP 命名空间下。但是var module = APP.define('module.example', function () { /*...*/ }) 有效。这也有效:

APP.define = function( name, definition ) {
    var namespace = APP.namespace( name );
    var module    = definition();

    for (var prop in module) {
        if (module.hasOwnProperty[prop]) {
            namespace[prop] = module[prop];
        }
    }
    return namespace;
};

我缺少关于对象引用或回调范围的某些内容。

【问题讨论】:

    标签: javascript module namespaces


    【解决方案1】:

    当您将 var namespace 分配给 APP.namespace( name ) 时,您会通过引用获得命名空间的最后一部分,但是 namespace = definition() 只是将您的命名空间变量重新定义为 definition 函数的结果。

    您可以合并您的 APP.namespaceAPP.define,以便您的前最后父母将命名空间的最后一部分作为属性分配给 definition 函数

    代码是:

    var APP = APP || {};
    APP.define = function( nsString, definition) {
    
        var parts  = nsString.split('.'),
            parent = this,
            i;
    
        if (parts[0] === 'APP') {
            parts = parts.slice(1);
        }
    
        for ( i = 0; i < parts.length - 1; i++ ) {
            if (typeof parent[parts[i]] === 'undefined') {
                parent[parts[i]] = {};
            }
            parent = parent[parts[i]];
        }
    
        parent[parts.pop()] = definition();
    };
    

    【讨论】:

    • 可能在if (parts[0] === 'APP')..部分代码中需要if(parts.length === 0) return;,但这就是细节
    猜你喜欢
    • 1970-01-01
    • 2015-01-22
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 2023-03-17
    • 1970-01-01
    • 2021-05-19
    相关资源
    最近更新 更多