I'm currently working on a piece of code that was put together by someone else on my team. All of his logic was in the index.html
file, so I'm trying to factor it out into a modular library. Part of the reason is that I now need to include an AJAX and UI library and I want to avoid collisions. I'm not a JavaScript programmer by any stretch of the imagination, so I have been working to understand the process of moving the code to separate files.
The goal of my endeavor is to factor out the code my team member wrote into a separate JavaScript file. The code should be namespaced so that after I import it I can call methods by namespace.method()
instead of calling method()
directly. This is to prevent collissions with other code. Furthermore, I need to be able to extend this namespace through other files. So including another file should allow me to call namespace.submodule.method()
.
The two articles I've been working with are Namespacing in JavaScript and JavaScript Module Pattern: In-Depth. To start with I just copied the entire script from the index.html
page into its own file. I then re-arranged the code to be under an anonymous self-executing function with a single argument which is the instance. Every exposed variable or method is then placed under a generic variable module
which is assigned as:
var module = instance || {};
The self-executing anonymous function is passed a variable already defined above it in the code to assign itself to.
The problem is that the singleton created by this code has public variables but no public methods. So, I can call namespace.variable
without any problem, but if I try to call namespace.method()
, I get an undefined error. I need help understanding exactly what syntax features of the language are making the variables public but not the methods.
I've made my current work available as a gist to facilitate viewing.