有没有“简明扼要"的?在 JavaScript 中进行命名空间的方法?

2022-01-14 00:00:00 namespaces javascript

我经常遇到将所有 JavaScript 放在 namespace 结构中的网站:

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 */ } } }

这是一个变量 namespaces 被分配了一个对象字面量.该对象包含一个属性: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.

相关文章