"JavaScript Namespacing"是什么意思? [英] What is meant by 'JavaScript Namespacing'?

查看:123
本文介绍了"JavaScript Namespacing"是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
JavaScript名称空间

Possible Duplicate:
Javascript Namespacing

我对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 Namespacing"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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