<!-- Notes : Implementing namespaces One problem to watch for is the pollution of the global namespace. As your program gets larger and libraries are added, more entries are added to the global object. You can implement the namespace pattern to solve the problem. object literal syntax is used to create an empty object and assign it to myApp. Everything else is added to the object. Although only one entry is made in the global namespace, all the members of myApp are globally accessible.
-----------------------------------------------------------------------
The difference is that the namespace is a singleton object, so you create a single instance for the namespace. You don’t need to worry about functions defined in the constructor function consuming additional memory for each instance because there is only one instance. you might want to have logic to create the namespace object only if it hasn’t been created. In the following example, the code for myApp is modified to create the namespace object if it doesn’t already exist. This code uses the OR operator to create a new object if myApp does not have a value.
---------------------------------------------------------------------
An IIFE (pronounced iffy) is an anonymous function expression that has a set of parentheses at the end of it, which indicates that you want to execute the function. The anonymous function expression is wrapped in parentheses to tell the JavaScript interpreter that the function isn’t only being defined; it’s also being executed when the file is loaded. (function(){}()); JavaScript doesn’t have a namespace keyword -->
JavaScript
/*var customNamespaceI = {};
var customNamespaceII = customNamespaceII || {};
customNamespaceI.car = function (year, makemodel) {
console.log(makemodel + "---" + year)
};*/
/* Best pattern to create namespace is by creating it in an IIFE*/ (function () {
this.customNamespaceIII = customNamespaceIII || {};
var namespace = this.customNamespaceIII;
var name = 'Sukanya';
namespace.showName = function () {
console.log(this.name);
};
}());
customNamespaceIII.showName();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.