chopper draw lion4
chopper draw lion4

Reputation: 13507

What is the relationship between namespace and lexical scope?

From my understanding lexical scope is a subset of the name space. What is the relationship between namespace and lexical scope?

Upvotes: 2

Views: 338

Answers (1)

Ben Aston
Ben Aston

Reputation: 55769

Namespaces are organisational units of code. Typically they are implemented in JavaScript by using properties on object literals, but there are more complicated implementations.

Simple example:

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();

Lexical scope is a completely orthogonal concept and relates the the visibility of variables within a piece of code. Scope is defined by functions in JavaScript. Very modern implementations of JavaScript also include mechanisms for block scoping, but you will not see this used very often in the wild.

Example:

function f() {
  var x = 'foo';
}

console.log(x); // undefined because the scope of x is the function f.

Upvotes: 2

Related Questions