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

What is meant by #39;JavaScript Namespacing#39;?(“JavaScript 命名空间是什么意思?)
本文介绍了“JavaScript 命名空间"是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

可能重复:
Javascript 命名空间

我对 JavaScript 很陌生,想知道是否有人可以很好地描述 JavaScript 命名空间的含义?

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

还有任何资源,例如文章等,在这个主题上非常受欢迎.

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

推荐答案

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

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:

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

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

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

MyApplication.myFunc();

同样,var1 总是被访问为:

Likewise, var1 always accessed as:

console.log(MyApplication.var1);

在此示例中,我们所有应用程序的代码都已在 MyApplication 中命名空间.因此,我们的变量与其他库创建的或 DOM 创建的变量发生冲突的可能性要小得多.

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.

这篇关于“JavaScript 命名空间"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

SCRIPT5: Access is denied in IE9 on xmlhttprequest(SCRIPT5:在 IE9 中对 xmlhttprequest 的访问被拒绝)
XMLHttpRequest module not defined/found(XMLHttpRequest 模块未定义/未找到)
Show a progress bar for downloading files using XHR2/AJAX(显示使用 XHR2/AJAX 下载文件的进度条)
How can I open a JSON file in JavaScript without jQuery?(如何在没有 jQuery 的情况下在 JavaScript 中打开 JSON 文件?)
quot;Origin null is not allowed by Access-Control-Allow-Originquot; in Chrome. Why?(“Access-Control-Allow-Origin 不允许 Origin null在铬.为什么?)
How to get response url in XMLHttpRequest?(如何在 XMLHttpRequest 中获取响应 url?)