命名空间和词法范围之间的关系是什么

What is the relationship between namespace and lexical scope?

本文关键字:关系 是什么 之间 范围 词法 命名空间      更新时间:2023-09-26

据我了解,词汇范围是名称空间的子集。命名空间和词法范围之间的关系是什么?

命名空间

是代码的组织单元。通常,它们是通过使用对象文字上的属性在 JavaScript 中实现的,但还有更复杂的实现。

简单的例子:

var myApp = {}; // Root 'namespace'.
myApp.services = {}; // 'Namespace' for service constructor functions.
myApp.controllers = {}; // 'Namespace' for controller constructor functions.
myApp.controllers.UserController = function() { /* ... */ };
// Usage.
var userController = new myApp.controllers.UserController();

词法范围是一个完全正交的概念,它与一段代码中变量的可见性相关联。范围由 JavaScript 中的函数定义。非常现代的 JavaScript 实现还包括块范围的机制,但你不会看到它在野外经常使用。

例:

function f() {
  var x = 'foo';
}
console.log(x); // undefined because the scope of x is the function f.