Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the syntax for a JavaScript sub namespaces/class inside current namespace/class?

Tags:

javascript

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?

like image 974
Ally Avatar asked Oct 06 '22 17:10

Ally


1 Answers

Perhaps your looking for something like this...

This will allow you to have the following syntax tinyFramework.Utilities.Storage.setItem() tinyFramework.Elements.Modals.createModal()

var tinyFramework = {

    Utilities: {
        Storage: {
            setItem: function(){
            //do stuff
            },

            getItem: function(){
            //do stuff
            }
        },
        Helpers: {

        }
    },

    Elements: {

        Modals: {

            createModal: function(){
            },
            closeModal: function(){
            }
        }
    }
}
like image 64
afreeland Avatar answered Oct 10 '22 04:10

afreeland