有没有“简洁”的说法。在JavaScript中进行命名空间的方法? [英] Is there a "concise" way to do namespacing in JavaScript?

查看:76
本文介绍了有没有“简洁”的说法。在JavaScript中进行命名空间的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常遇到将所有JavaScript放在命名空间结构中的网站:

I've frequently encountered sites that put all of their JavaScript inside a namespace structure along the lines of:

namespaces = { com : { example: { example.com's data} }

然而,相对于其他命名空间框架安全地设置它似乎需要相对大量的代码(定义为> 2行)。我想知道是否有人知道这样做的简洁方法?此外,是否有相对标准/一致的结构方式?例如, com 命名空间是直接附加到全局对象,还是通过命名空间对象附加?

However, setting this up safely with respect to other namespaced frameworks seems to require a relatively hefty amount of code (defined as > 2 lines). I was wondering whether anyone knows of a concise way to do this? Furthermore, whether there's a relatively standard/consistent way to structure it? For example, is the com namespace directly attached to the global object, or is it attached through a namespace object?

推荐答案

Javascript没有独立的命名空间。它具有可以提供解析名称和对象的范围的功能,这些功能可以对给定范围内可访问的命名数据做出贡献。

Javascript doesn't have stand-alone namespaces. It has functions, which can provide scope for resolving names, and objects, which can contribute to the named data accessible in a given scope.

以下是您的示例,已更正:

Here's your example, corrected:

var namespaces = { com: { example: { /* example.com's data */ } } }

这是一个变量名称空间被分配了一个对象文字。该对象包含一个属性: com ,一个具有一个属性的对象: example ,一个可能包含一些有趣内容的对象。

This is a variable namespaces being assigned an object literal. The object contains one property: com, an object with one property: example, an object which presumably would contain something interesting.

因此,您可以键入类似 namespaces.com.example。 somePropertyOrFunctionOnExample 的内容,它们都可以正常工作。当然,这也是荒谬的。你没有一个分层命名空间,你有一个包含一个对象的对象,该对象包含你真正关心的东西。

So, you can type something like namespaces.com.example.somePropertyOrFunctionOnExample and it'll all work. Of course, it's also ridiculous. You don't have a hierarchical namespace, you have an object containing an object containing an object with the stuff you actually care about.

var com_example_data = { /* example.com's data */ };

同样有效,没有无意义的层次结构。

That works just as well, without the pointless hierarchy.

现在,如果您实际上想要构建层次结构,您可以尝试这样的事情:

Now, if you actually want to build a hierarchy, you can try something like this:

com_example = com_example || {};
com_example.flags = com_example.flags || { active: false, restricted: true};

com_example.ops = com_example.ops || (function()
    {
       var launchCodes = "38925491753824"; // hidden / private
       return {
         activate: function() { /* ... */ },
         destroyTheWorld: function() { /* ... */ }
       };
    })();

...这是恕我直言,相当简洁。

...which is, IMHO, reasonably concise.

这篇关于有没有“简洁”的说法。在JavaScript中进行命名空间的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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