创建JavaScript命名空间的最佳方法是什么? [英] What's the best way to create a JavaScript namespace?

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

问题描述

我还没有在互联网上找到一种在JavaScript中创建命名空间的常用方法。

I have not yet found a common way on the Internet for creating a namespace in JavaScript.

创建命名空间的最佳方法是什么(请列出任何垮台特定的方法可能有)。

What's the best way to create a namespace (and please list any downfalls that particular approach might have).

推荐答案

在JavaScript中,命名空间只能通过对象文字来实现,这可以像这个:

In JavaScript, namespaces can only be achieved through object literals, which can be as simple as this:

var MyNS = {
    f1: function() {...},
    f2: function() {...}
};

正如其他人试图展示的那样,如果你想在命名空间内提供私有范围(这是建议),以下方法是最合适的:

As others have attempted to show, if you want to provide a private scope within your namespace (which is suggested), the following method is the most appropriate:

var MyNS = (function() {
    var private1 = "...", 
        private2 = "...";

    return {
        f1: function() {...},
        f2: function() {...}
    }
})();

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

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