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?
- In the first iteration of the loop we have parts[i] == "myproject" and root[parts[i]] == {}
- So the assignment is root = {} ???
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?