这两种方法命名空间有什么区别? [英] What's the difference between these two approaches to namespacing?

查看:112
本文介绍了这两种方法命名空间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码目录中有第一个文件,如下所示

I've got the first file in my code directory as follows

myNamespace.js

var myNamespace = {};

然后我的后续文件可以看作以下两种方式之一。

Then my subsequent files can look as one of the two following ways.

第一

(function (ns) {
    ns.DoStuff = function(){
        // do stuff
    }
})(myNamespace);

myNamespace.DoStuff = function(){
    //do stuff
}

那么这两种方法有什么区别呢?两个似乎都为我工作。是否有更广为接受的惯例?

So what is the difference between these two methods? Both seem to work for me. Is there a more generally accepted convention?

对不起,仍然是javascript的新

推荐答案

您的第一个错误,您使用了,我确定您的意思是 ns

You have an error in your first one, you've used this where I'm pretty sure you meant ns:

ns.DoStuff = function() {
};

离开,你的第一种方法往往更好,因为你创建了一个很好的小范围函数对于自己,这允许您有私有数据和函数可用于您在命名空间上创建的所有公共方法,而不使它们成为全局变量。例如:

Leaving that aside, your first approach tends to be better because you've created a nice little scoping function for yourself, which allows you to have private data and functions available to all of the public methods you create on your namespace, without making them globals. E.g.:

(function(ns) {
    function privateFunction() {
    }

    ns.DoStuff = function() {
        privateFunction();   // <=== works fine
    };

})(myNamespace);]
privateFunction(); // <=== doesn't work, because it's private

我喜欢这样做部分原因是因为我有反对匿名功能,所以我不会如上所述定义 DoStuff ,而是这样:

I like doing it that way partially because I have thing against anonymous functions, and so I wouldn't define DoStuff as above, but rather like this:

(function(ns) {
    ns.DoStuff = Namespace$DoStuff;
    function Namespace$DoStuff() {
    }
})(myNamespace);

现在我已经分配给 myNamespace.DoStuff 有一个正确的名称,这有助于我在我调试我的代码。但是该名称不会污染全局命名空间,这有助于我保持理智,避免与其他代码冲突。

Now the function I've assigned to myNamespace.DoStuff has a proper name, which helps me out when I'm debugging my code. But that name doesn't pollute the global namespace, which helps me stay sane and avoid conflicts with other code.

这篇关于这两种方法命名空间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆