为您的 JavaScript 添加命名空间





0/5 (0投票)
JavaScript 是一种面向对象编程语言,但它也是一种函数式编程语言,这与一些更熟悉的
JavaScript 是一种面向对象编程语言,但它是一种 函数式编程语言,这与一些更熟悉的经典编程语言(如 C#、VB.NET、C++ 和 Java)不同。
目前,JavaScript 不支持枚举、访问器(私有、公共、受保护等)、类或命名空间。但是,所有这些都可以通过 JavaScript 对象、闭包、函数和 lambda 表达式来实现。
重点讨论 JavaScript 命名空间。 默认情况下,加载到页面中的所有 JavaScript 都是全局的。命名空间是一种重要的防御性编程技术,因为它最大限度地减少了脚本相互干扰的风险。
这种方法借鉴自 模块和命名空间(第 10 章),出自 JavaScript:权威指南,并且与 Yahoo! 使用的方法非常相似。
// Create the namespace object. Error checking omitted here for brevity.
var myNameSpace;
if (!myNameSpace) myNameSpace = {};
myNameSpace.myPseudoClass = {};
//JavaScript doesn't support classes,
// so let's avoid confusing people and call this a Pseudo Class
// Don't stick anything into the namespace directly.
// Instead we define and invoke an anonymous function to create a closure
// that serves as our private namespace. This function will export its
// public symbols from the closure into the myNameSpace object
// Note that we use an unnamed function so we don't create any other
// global symbols.
(function() { // Begin anonymous function definition
// Nested functions create symbols within the closure
function displayMyMessage() { alert(myMessage); }
// Local variable are symbols within the closure.
// This one will remain private within the closure
var myMessage = 'Hello World';
// This function can refer to the variable with a simple name
// instead of having to qualify it with a namespace
function getMyMessage() { return myMessage; }
// Now that we've defined the properties we want in our private
// closure, we can export the public ones to the public namespace
// and leave the private ones hidden here.
var ns = myNameSpace.myPseudoClass;
ns.displayMyMessage = displayMyMessage;
ns.getMyMessage = getMyMessage;
})(); // End anonymous function definition and invoke it
然后我们可以像这样从命名空间外部调用 displayMyMessage
<button onclick="myNameSpace.myPseudoClass.displayMyMessage()">测试我</button>