A namespace is a container which allows developers to bundle up all functionality under a unique, application-specific name. In JavaScript a namespace is just another object containing methods, properties and objects.
It is very important to note that there is no language-level
difference between regular object and namespaces as there is in some
other object-oriented languages.
The idea behind creating a namespace in JavaScript is simple: one
global object is created and all variables, methods and functions become
properties of that object. Use of namespaces also minimizes the
possibility of name conflicts in an application.Let's create a global object called MYAPP:
// global namespace
var MYAPP = MYAPP || {};
Here in above code sample we have first checked whether MYAPP is
already defined (either in same file or in another file). If yes, then
use the existing MYAPP global object, otherwise create an empty object
called MYAPP which will encapsulate method, functions, variables and
objects.We can also create sub-namespaces:
// sub namespace
MYAPP.event = {};
Below is code syntax for creating namespace and adding variable, function and method:// Create container called MYAPP.commonMethod for common method and properties
MYAPP.commonMethod = {
regExForName: "", // define regex for name validation
regExForPhone: "", // define regex for phone no validation
validateName: function(name){
// Do something with name, you can access regExForName variable
// using "this.regExForName"
},
validatePhoneNo: function(phoneNo){
// do something with phone number
}
}
// Object together with the method declarations
MYAPP.event = {
addListener: function(el, type, fn) {
// code stuff
},
removeListener: function(el, type, fn) {
// code stuff
},
getEvent: function(e) {
// code stuff
}
// Can add another method and properties
}
// Syntax for Using addListener method:
MYAPP.event.addListener("yourel", "type", callback);
Not sure who copied who but this is literally just a copy of MDN article https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
ReplyDeleteNot sure who copied who but this is literally just a copy of MDN article https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
ReplyDelete