2.1 Javascript Functions: Creating a namespace

Last week we learned how to create javascript functions.  For example, to create a placemarker, the function was:

When you create a function with this method, the function gets put in what’s called the “global” namespace, meaning that it can be accessed by anybody and everything that will use your code. While this may not seem like a bad thing, imagine if you were sharing your code with your classmates, and they also had the exact same function name declared (also imagine that both functions, though named the same, actually did something slightly different). This would not bode well… It’s like having twin babies, and giving them the exact same name. In order to avoid such confusion, it is important to declare a unique namespace to any functions you may be creating.

Creating a namespace

Let’s say that Bob is a coder. Bob decides to create a unique namespace called “bob” for all the functions that he creates. Instead of creating the function in the global namespace (as in the code above), he first declares his namespace as a new javascript object:

The squiggly marks (“{ }”) defines this as an object, that allows you to define functions inside of the object, or in this case, using the “bob” namespace. Once you have declared the namespace, you can add functions to it as follows:

You would then access this function as follows:

Putting it all together

So, let’s put all the pieces together, and rewrite last week’s assignment using a namespace. Notice that I have created a namespace called “yoh”, and therefore all functions must be called with a leading “yoh” following by a period “.” followed by the function name. I have also put the “initialize()” function under the “yoh” namespace, and moved the “yoh.createMarker” function outside of the yoh.initialize() function.

Leave a Reply