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.. :)
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With