“JavaScript 命名空间”是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8523231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:42:36  来源:igfitidea点击:

What is meant by 'JavaScript Namespacing'?

javascriptnamespacesjavascript-namespaces

提问by bc17

Possible Duplicate:
Javascript Namespacing

可能的重复:
Javascript 命名空间

Im pretty new to JavaScript and was wondering if anyone could give me a good description of what is meant by JavaScript Namespacing?

我对 JavaScript 还很陌生,想知道是否有人能给我一个关于 JavaScript 命名空间含义的很好的描述?

Also any resources e.g. articles etc, are much appreciated on the subject.

此外,任何资源,例如文章等,都非常感谢这个主题。

回答by Michael Berkowski

JavaScript is designed in such a way that it is very easy to create global variables that have the potential to interact in negative ways. The practice of namespacing is usually to create an object literal encapsulating your own functions and variables, so as not to collide with those created by other libraries:

JavaScript 的设计方式是很容易创建可能以负面方式交互的全局变量。命名空间的做法通常是创建一个对象字面量来封装你自己的函数和变量,以免与其他库创建的那些发生冲突:

var MyApplication = {
  var1: someval,
  var2: someval,
  myFunc: function() {
    // do stuff
  }
};

Then instead of calling myFunc()globally, it would always be called as:

然后myFunc()它不会被全局调用,而是总是被调用为:

MyApplication.myFunc();

Likewise, var1always accessed as:

同样,var1始终访问为:

console.log(MyApplication.var1);

In this example, all of our application's code has been namespaced inside MyApplication. It is therefore far less likely that our variables will collide with those created by other libraries or created by the DOM.

在这个例子中,我们应用程序的所有代码都在MyApplication. 因此,我们的变量与其他库创建的或由 DOM 创建的变量发生冲突的可能性要小得多。

回答by Justin Niessner

For a quick run down (including techniques), give this a read:

要快速了解(包括技术),请阅读以下内容:

Namespacing in JavaScript

JavaScript 中的命名空间

回答by CaffGeek

I use this namespacing technique, along with "use strict" outlined by Crockford

我使用这种命名空间技术,以及Crockford概述的“严格使用”

var MyNamespace = (function () {
    "use strict"; 

    function SomeOtherFunction() {

    }

    function Page_Load() {

    }

    return { //Expose 
        Page_Load: Page_Load,
        SomeOtherFunction: SomeOtherFunction
    };
} ());

MyNamespace.Page_Load();

回答by Mihalis Bagos

Read up on a simple tutorial Here

这里阅读一个简单的教程

Namespacing is used to avoid polluting the global namespace (no window. variables). In truth, each namespace is just a big variable, that has many properties and methods.

命名空间用于避免污染全局命名空间(无窗口.变量)。事实上,每个命名空间只是一个大变量,有很多属性和方法。

This happens, because in javascript you can have whole functions (methods) as variables

发生这种情况,因为在 javascript 中,您可以将整个函数(方法)作为变量