Reputation: 10699
I'm taking an online class on Javascript and can't seem to find any separation between a namespace and an object without a constructor function.
For example, below is the book's example for a namesapce
var MyNamespace = {
myFunction1: function(someParameters) {
// Implementation code…
},
myFunction2: function(someParameters) {
// Implementation code…
},
message: "Hello World",
count: 42
}
Then, using object literal notation here is the example for an object
var objectName = {
property1: value1,
property2: value2,
};
Syntactically they look almost exactly the same. Both are declared using the var
keyword and, generally, intended to be scoped globally. Both also define members publicly. The object example uses a line delimiter but... not sure that matters too much.
The properties are also accessed the same using dot notation:
MyNamespace.myFunction1
objectName.property1
They can also share the same public property names. For example, the example below give the appropriate values for .property1
for both the namespace and the object.
var MyNamespace = {
property1: "nsValue"
}
var objectName = {
property1: "objValue"
};
console.log(MyNamespace.property1);
console.log(objectName.property1);
While there's a (good) chance I'm missing something it seems for all intents and purposes there is no difference between a JavaScript namespace and an object created using object literal notation. What am I missing?
Upvotes: 0
Views: 375
Reputation: 954
A "namespace" is just a grouping of objects and functions. An object literal can be used to implement a Namespace. Conventionally, when an object is used in this way, you'll capitalize the first letter just the same as you would a function constructor (as you have done here with MyNamespace). If your app requires use of global scope, it's good practice to use a namespace like this to prevent name conflicts (just as jQuery uses $ as a namespace in order to access all the methods and properties of its API).
Upvotes: 2
Reputation: 724
Object literal is one of the ways of achieving the concept of namespacing in JavaScript. I believe that when you talk about namespacing, you are referring to the concept of avoiding collisions with other objects and variables. However, namespacing can be achieved using other patterns as well like using an IIFE (Immediately Invoked Function Execution). One of the most frequent examples of namespacing is when you are working with jQuery. Usually to prevent conflicting uses of the $
variable, it is recommended that you pass in the jQuery
variable to the anonymous function and then assign it to the $
variable.
(function ( $ ) {
var shade = "#556b2f";
$.fn.greenify = function() {
this.css( "color", shade );
return this;
};
}( jQuery ));
This basically ensures that the $
variable will always be assigned to the jQuery
object within that function.
Upvotes: 2