Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Namespace Declaration

Tags:

javascript

I created a javascript class as follow:

var MyClass = (function() {    function myprivate(param) {       console.log(param);    }     return {       MyPublic : function(param) {          myprivate(param);       }    }; })();  MyClass.MyPublic("hello"); 

The code above is working, but my question is, how if I want to introduce namespace to that class.

Basically I want to be able to call the class like this:

Namespace.MyClass.MyPublic("Hello World"); 

If I added Namespace.MyClass, it'll throw error "Syntax Error". I did try to add "window.Namespace = {}" and it doesn't work either.

Thanks.. :)

like image 659
heisthedon Avatar asked Mar 24 '10 00:03

heisthedon


People also ask

What is namespace in JavaScript with example?

Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts.

What is declare namespace?

Namespace Declaration We can create a namespace by using the namespace keyword followed by the namespace_name. All the interfaces, classes, functions, and variables can be defined in the curly braces{} by using the export keyword. The export keyword makes each component accessible to outside the namespaces.

Why do we use namespace in JavaScript?

JavaScript “namespace” is a programming paradigm that is utilized for assigning scope to the identifiers such as variables and function names. It is used to prevent collisions between the same-named variables and functions.


1 Answers

Usually I'd recommend doing this (assuming Namespace is not defined elsewhere):

var Namespace = {}; Namespace.MyClass = (function () {   // ... }()); 

A more flexible, but more complex, approach:

var Namespace = (function (Namespace) {    Namespace.MyClass = function() {         var privateMember = "private";        function myPrivateMethod(param) {          alert(param || privateMember);        };         MyClass.MyPublicMember = "public";        MyClass.MyPublicMethod = function (param) {           myPrivateMethod(param);        };    }    return Namespace }(Namespace || {})); 

This builds Namespace.MyClass as above, but doesn't rely on Namespace already existing. It will declare and create it if it does not already exist. This also lets you load multiple members of Namespace in parallel in different files, loading order will not matter.

For more: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

like image 176
bcherry Avatar answered Sep 22 '22 21:09

bcherry