Overview
In Javascript, it is a good practice to wrap your code files within an anonymous
function like (function(){ ... })()
. The purpose is to namespace your codes
and to avoid name collisions.
There are different ways to do this. The codes below will show you how to do it using the Module pattern.
Class like behaviour using Module pattern
The codes are self-explanatory. It shows you how private and public members, and methods are implemented.
var MODULE = (function () { function Person(name, age){ var my = {}; // my is the Person object itself. // Private. var privateVariable = age; function privateMethod() { return privateVariable; }; // Public. my.name = name; my.moduleMethod = function () { return my.name; }; my.moduleMethodAccessPrivate = function () { return privateMethod(); }; return my; } return { // This function allows you to create multiple instance of this module. createPerson: function(name, age) {return new Person(name, age);} }; }());
Using the module pattern
var john = MODULE.createPerson('john', 22); alert(john.name); alert(john.moduleMethod()); alert(john.moduleMethodAccessPrivate()); var nikki = MODULE.createPerson('nikki', 55); alert(nikki.name); alert(nikki.moduleMethod()); alert(nikki.moduleMethodAccessPrivate());
Reference
- Excellent explanation of Public, Private, Privileged methods by Douglas Crockford http://www.crockford.com/javascript/private.html
- JavaScript Module Pattern: In-Depth: http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
- Purpose of anonymous function explained: https://stackoverflow.com/a/2421949
- How to set up JavaScript namespace and classes properly?: https://stackoverflow.com/a/11651588
- How anonymous function is executed: http://benalman.com/news/2010/11/immediately-invoked-function-expression/
- Different way to namespace: https://www.oreilly.com/library/view/learning-javascript-design/9781449334840/ch13s15.html