Avinash
Avinash

Reputation: 31

How to create a top level namespace in javascript

So now I have 3 javascript files. item.js, items.js, main.js. Their structure is like

var item = (function(){
        //some functions inside and return statement
})();

same goes for main and items.
now the hierarchy of the files are, as I understood,
window.item, window.items, window.main
but I want to change it to 

window.todo.items
window.todo.item
window.todo.main

I have searched a lot on namespaces but couldn't find the answer. Any suggestions will be appreciated. Thank you

Upvotes: 0

Views: 174

Answers (3)

Andreas Linnert
Andreas Linnert

Reputation: 577

First of all: there are no namespaces in JavaScript. You can somewhat simulate namespaces using objects.

First you have to make sure that your todo object does exist. (You cannot bulk-create properties)

window.todo = {};

Then you can add properties to that todo object:

window.todo.item = (function () { ... })();
// or
window.todo.item = item;

You can also initialize properties while creating the todo object:

window.todo = {
    item: (function { ... })()
};
// or
window.todo = {
    item: item
};

Upvotes: 0

Kunvar Singh
Kunvar Singh

Reputation: 1885

Basically js is depend upon the priority of the js file, so make sure that, decendent file don't have the depency on above file,

Upvotes: 0

EKW
EKW

Reputation: 2113

Well, first you'd need to define todo

window.todo = {};

Then you'd need to add each file's object to it

window.todo.item = (function(){
    //some functions inside and return statement
})();

Upvotes: 1

Related Questions