如何允许最终用户为此模式定义多个命名空间扩展级别

How to allow the end user to define multiple namespace-extension levels for this pattern?

本文关键字:命名空间 扩展 定义 模式 何允许 用户      更新时间:2023-09-26

以这段代码为例:

(function(foo) {
    foo.init = function() {};
    // other public/private methods here.
    return foo;
}(window.FOO = window.FOO || {}));

我是这样称呼的:

FOO.init();

是否可以允许用户定义什么是FOO

换句话说,我需要允许多个window.FOO实例;例如,像window.BILLYwindow.BAZ(或者,它应该是window.billy.FOOwindow.baz.FOO?)。

换句话说,有没有一种优雅的方法(允许用户)使用上述构造和初始化的变体来命名空间一个"命名空间"?

如果我

理解正确,您想更改上面的代码,以便FOO的名称是动态的。您可以使用 [] 属性访问器执行此操作:

function initFoo(fooName) {
    (function(foo) {
        foo.init = function() {};
        // other public/private methods here.
        return foo;
    }(window[fooName] = window[fooName] || {}));
}
initFoo('FOO');
initFoo('BILLY');

但我不确定这有什么意义,你的例子非常抽象。

首选

windows.billy.FOOwindows.baz.FOO

通读 Addy Osmani 的基本 JS 命名空间模式以加快速度(最相关的部分:深度对象扩展)。

干杯!

你可能

想看看RequireJS: http://requirejs.org/docs/start.html

它可能具有您正在寻找的最终用户功能。