Ugur
Ugur

Reputation: 2044

Trying to understand JavaScript code // Namespaces

I have a legacy PHP project with lots of JavaScript code that I try to understand.

Each of these JS files start with this code fragment:

var myproject = myproject || {};
registerNamespace = function(namespace) {
    var parts = namespace.split(".");
    var root = window;
    for ( var i = 0; i < parts.length; i++) {
        if (typeof root[parts[i]] == "undefined") {
            root[parts[i]] = {};
        }
        root = root[parts[i]];
    }
};

registerNamespace('myproject.main');

So we create a namespace called myproject in the first line.

The function registerNamespace splits a dot separated string into its parts and adds {part: {}} to the var "root" (which happens to be a copy (or a reference to?) the global namespace of the browser (that is: "window")).

So if a part is not in "root" already (== "undefined"), then we'll add the key/value pair {part: {}} to "root".

Now the thing that I don't understand: After the if statement we have an assignment that assigns root[parts[i]] to the variable "root" itself. Why?

What is that last assigment good for?

Also: Is the variable root a reference to the global namespace "window"? So anything I write to "root" will write to "window"? Or is it a copy?

Can anyone enlighten me?

Upvotes: 0

Views: 140

Answers (1)

Jonathan Dupr&#233;
Jonathan Dupr&#233;

Reputation: 828

root is used as a reference.

First, it points to the global 'window' object. If myproject is not defined as a property of window, window.myproject is assigned to a new object.

Then root is used to point to the window.myproject. If main is not defined as a property of window.myproject, window.myproject.main assigned to a new object.

If the registerNamespace function had been called with, say, the string 'myproject.main.mynamespace', then root would have been reassigned to reference window.myproject.main, and so on.

root = window // root now points to the window object
root['main'] = {} // a new object is created, and root['main'] now points to it
root = root['main'] // root now points to root['main']

Upvotes: 1

Related Questions