This is my first post on StackOverflow. This community has provided me with some great insights into lots of different coding questions over the years. So since I’ve been stuck on this particular task in JS for days, I decided I’d lean on this great community and see what sort of help I could get on my question.
I saw a pretty good post here that actually was close to what I want (post here), but unfortunately I need to create multiple instances of an Object that is within a namespace, which that example doesn’t help with.
Here’s what I am attempting to do:
if (!myNamespace) {
var myNamespace = {};
}
// Object for my namesapce
myNamespace.Item = function() {
return {
Initialize: function(title,details) {
// setting members of this Object
this.title = title;
this.details = details;
},
Display: function() {
this.Position();
this.Show();
},
Position: function() {
// position my item in the DOM
},
Show: function() {
// show my item in the DOM
}
};
}();
// another Object for my namesapce
myNamespace.Basket = function() {
return {
Initialize: function(title,details,code) {
// setting members of this Object
this.items = [];
},
Add: function(item) {
this.items[items.length] = item;
}
};
}();
var Item = new myNamespace.Item; // the code fails to create a new instance of this Object
Item.Initialize("New Item Title","New Item Desc.");
Item.Display();
var Item2 = new myNamespace.Item; // the code fails to create a new instance of this Object
Item2.Initialize("New Item Title2","New Item Desc. 2");
Item2.Display();
I’m fairly sure I am thinking of Singleton vs. Class incorrectly. A nice code example with the correct nesting/structure would help SO much! THANKS IN ADVANCE!
The problem is that
myNamespace.Itemis not a function, is an object, because you have a function that is immediately executed.You can for example, add the methods to the current object:
Or use the
prototypeproperty of the constructor function, to make the object instances created with thenewoperator inherit those methods:Or a slightly shorter syntax:
The benefit of using the
prototypeproperty is that the methods exist only in themyNamespace.Item.prototypeobject, while in the first example, each object will have its own function instances which is less memory-efficient.