There are a lot of different ways to structure your Javascript code (and the most popular one remains no structure at all ). One of the most used patterns out there is the Module pattern. Instead of giving you a long explanation, let me show you a short sample:
Learn it, love it…
var module=(function(){ var helloText='Hello world' function sayHello(){ alert(helloText); } return { sayHello: sayHello}; })(); module.sayHello();
What’s happening inside this code?
- I create a JavaScript function that I immediately invoke. The result is assigned to the variable ‘module’.
- Inside this function I create a variable called ‘helloText’. As JavaScript uses function scope instead of block scope, this variable is available everywhere inside this function but not outside of it.
- I add a function ‘sayHello’, this function is also only accessible inside the ‘Module’ function.
- As a last step I create a new JavaScript object with a function sayHello on it that refers to the internal ‘sayHello’ function I’ve just created. This object is then returned. When I immediately invoked the function in step 1 I got the object back we’ve created with one public function ‘sayHello’.
Learn it, love it…