Friday, April 2, 2010

How to properly write JavaScript libraries

I've seen JavaScript code written in all the possible ways. The reason there are so many ways to do it is because JavaScript is incredibly flexible. But that flexibility makes people write really ugly code. Examples of ugly, unreadable, error-prone code:

(function(window, undefined) { var myLibrary = (function () { var someProp = "..."; function someFunc() { ... var myLibrary = (function () { var someProp = "..."; function someFunc() { ...

If you write JavaScript like that, stop. Here's the proper way to write JavaScript libraries:

function Example() { if (!(this instanceof Example)) { // in case whoever used this forgot to use the `new' keyword return new Example(); } Example.staticMethod(); this.instanceMethod(); // for any timeouts/events, do this: var instance = this; setTimeout(function() { instance.instanceMethod(); }, 200); } Example.staticMethod = function() { // do something here; } Example.prototype.instanceMethod = function() { // do something here } // instantiate the Example class: var example = new Example();

Isn't this much more beautiful? The reason for the instance variable needed in timeouts and events is that, in JavaScript, when handlers are called, they are called in the window context. That means that inside the handler, the keyword this refers to the global object window. By using the instance variable we are working around this, calling the handler with the correct context.

Inspired by this stackoverflow question.

No comments:

Post a Comment