I am trying to rewrite a JS web-application in a more object-oriented way.
Say I have a main object called Application:
var Application = (function(obj) {
obj.init = function() {
console.log("Application init");
};
obj.move = function() {
return {
left: function() { console.log("Move left"); },
right: function() { console.log("Move right"); }
}
}
return obj;
})(Application || {});
I'd like to add another method which could have multiple instances, so I'll need to add a prototype: (This happens in another file)
var Application = (function(obj) {
obj.child = function() {
return {
typeA: function() {
console.log("New child object of type A");
this.childID = Math.floor((Math.random() * 10) + 1); // Just a random number
},
typeB: function() {
console.log("New child object of type B");
this.childID = Math.floor((Math.random() * 10) + 1); // Just a random number
}
}
// This is where it goes wrong
obj.child.typeA.prototype = function() {
getID: function() { console.log(this.childID) }
}
};
return obj;
})(Application || {});
I problem is that I cannot access the prototype function getID
for typeA()
.
This is probably because of the way I have structured the application.
I'd like to be able to call the prototype method like so:
var a = Application.child.typeA();
a.getID();
How do I add a prototype for an object like this in a proper way?
I'm new to object-oriented Javascript and as there are so many ways to structure an object-oriented application in JS I pretty sure I am messing them up.