1

我一直在尽可能多地研究 Yahoo YUI 博客建议的模块模式。

我注意到 YUI 提供了创建新的空命名空间对象的能力,而无需覆盖现有的同名对象,如下所示:

YAHOO.namespace("myProject");

然后可以调用并使用YAHOO.myProject

(提醒:如果YAHOO.myProject已经存在则不会被覆盖)

如何在不使用 YUI 的情况下使用纯 javascript 实现类似的效果?

请尽可能详细地解释。

可以在此处找到完成此操作的完整 YUI 博客文章。

当我学习和加强我的 javascript 知识和技能时,我正在尝试创建自己的个人 javascript 库(即使我从不需要使用它)

4

3 回答 3

2

在您的示例中,它可以像这样工作:

if (!YAHOO.myProject) {
    YAHOO.myProject = {};
}
YAHOO.myProject.whatever = true;

或使用您自己的父模块名称:

var myModule = myModule || {};  // make sure parent is defined without overwriting
if (!myModule.myProject) {
    myModule.myProject = {};
}
myModule.myProject.whatever = true;

或者定义自己的命名空间函数:

function myNamespace(item) {
    if (!myModule[item]) {
        myModule[item] = {};
    }
}

myNamespace("myProject");
myNamespace.myProject.whatever = true;
于 2012-02-24T05:41:45.810 回答
1

问:如何在不覆盖另一个同名对象的情况下创建一个空的命名空间对象?

你不能。根据定义,同名不能同时引用新的空对象和现有对象。

如果您的意思是“我如何检查创建一个空的命名空间对象仅在它不存在的情况下,否则我想添加到现有的对象”,那么您只需执行以下操作:

if (!YAHOO.myProject)
   YAHOO.myProject = {};

// or you may see this variation:
YAHOO.myProject = YAHOO.myProject || {};

我不喜欢后者,但它经常用于实现与普通 if 语句相同的效果。

要进一步了解这一一般原则请查看这篇文章: http: //www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

更新:根据YUI API 文档YAHOO.namespace(),“返回指定的命名空间并在它不存在时创建它”的方法 - 你会注意到它比你正在阅读的博客的措辞要少得多,而且几乎支持我已经说过的话...

于 2012-02-24T05:46:41.930 回答
1

编辑刚刚意识到我没有直接回答你的问题。对不起!但是希望这将帮助您了解一些替代技术。

这是我不时使用的一种技术,例如当我想添加一次属性或函数并且不允许以后覆盖它时。

    var module = new function(){

        var modules = {}; //internal module cache

        return function(name, module){
            //return all modules
            if( !name ) return modules;

            //return specific module
            if( modules[name] ) return modules[name];

            //return the module and store it
            return modules[name] = module;
        }

    }

所以你可以像这样使用它:

//will store this since it doesn't exist
module('test', 'foo'); //Since 'test' doesn't exist on the internal 'modules' variable, it sets this property with the value of 'foo'

module('test'); // Since we aren't passing a 2nd parameter, it returns the value of 'test' on the internal 'modules' variable

module('test', 'bar'); //We are attempting to change the value of 'test' to 'bar', but since 'test' already equals 'foo', it returns 'foo' instead.

module(); // { 'test': 'foo' } //Here we aren't passing any parameters, so it just returns the entire internal 'modules' variable. 

要看的关键是我们正在使用'new function()'。这是在赋值时完成的,因为我们真的希望“模块”成为内部函数,而不是外部函数。但是为了为内部“var modules”变量创建一个闭包,外部函数必须在赋值时执行。

另请注意,您也可以将外部函数编写为自执行:

var module = function(){
    var modules = {};
    //other stuff
}();
于 2012-02-24T05:52:01.223 回答