Classy JavaScript - Best Practices

11. February 2010 13:26

Okay, so you really want to be able to have some of your JavaScript methods to have access to a variable that is private, but maintains state between calls. The first piece of knowledge, is that you can have the contents of a function execute itself at runtime.

(function(){ /*Your actions here*/ })();

This is a very common method of defining complex classes and libraries, that can have their own variables or methods that aren't otherwise available to the object model outside this closure. When you utilize "this" within the function's closure it will be default to the global object, which in the Browser DOM is "window".

(function(){
    this.test = "Test Value";
})();
alert(test); //alerts "Test Value"

Usually when creating libraries in JavaScript it's a good idea to create namespaces for your library. More...

Tracker1

Michael J. Ryan aka Tracker1

My name is Michael J. Ryan and I've been developing web based applications since the mid 90's.

I am an advanced Web UX developer with a near expert knowledge of JavaScript.