I've been working a lot with JavaScript lately and have created some large function collections. I've found the need to have sub functionality that I want to separate from the main library yet still be included in the main library but haven't found an elegant enough way to do this yet.
Here are a couple of examples that I use at the moment
So I usually setup my main library like this
// Main library
var animals = function(settings){
// Main library stuff
}
To add sub classes / sub functionality that's encapsulated separately but still part of the main library...
This is the first method using object literal notation
animals.prototype.dogs = {
addDog: function(){
// Can only access the dogs object
var test = this;
},
removeDog: function(){}
}
// Usage of the whole thing
var animalsInstance = new animals({a: 1, b: 3});
animalsInstance.dogs.addDog();
While I really like the syntax of this i can never really use it as there is no way to reference the animals instance inside any of the functions inside the dogs object. So I came up with this notation as a replacement
animals.prototype.dogs = function(){
var parent = this;
return {
addDog: function(){
// The animals instance
var test = parent;
// The dogs instance
var test2 = this;
},
removeDog: function(){}
}
}
// Usage
var animalsInstance = new animals({a: 1, b: 3});
animalsInstance.dogs().addDog();
Although now I can get access to the animals instance from inside all the sub functionality of the dogs functions I don't really like the slightly hacky way I've done it. Has anyone got any cleaner methods?