Pre – Pro JavaScript Design Patterns

March 10, 2008 at 6:38 pm (Coding, JavaScript) (, )

I just bought Pro JavaScript Design Patterns from Amazon for my birthday and it arrived today. Recently I have really got into JavaScript and decided on getting this book mostly because I enjoyed reading Dustin Diaz’s blog so much. The blog itself hasn’t had much recent content but it delivers a lot of very educational and enjoyable reads that are as validate as the day they were posted. I have never purchased a book about coding or even computing really, so this is a prototype to evaluate there benefits. I figured I would land some JavaScript design patterns that I like to use, very personally, so that after I finish the book I can compare how I code then. For the most part the techniques will be very basic but hopefully they benefit some web wonders.

Defining Functions

Usually you learn to define functions like so…
function doSomething() {
(...)
}

However, I like to define functions like so…
var doSomething = function() {
(...)
}

Semantically they are identical, but it’s just taken a preference recently. It keeps my code looking more consistent with the way I define objects (see literals below).

Literals

Sometimes it just seems ridiculous to define a new object (I don’t like using new to much (when you can use a literal)) …
var myString = new String('foo')
var myArray = new Array('foo','bar')
var myObject = new Object()

You probably already use some literals…
var myString = 'foo' //creates a string literal value
I like to additionally use these literals…
var myArray = ['foo','bar'] //creates an array literal, with values
var myObject = {} //creates an object literal

Object Initialisers

More commonly referred to as JavaScript Object Notation (JSON). Nearly all the JavaScript I write uses JSON. It’s a much better way of writing your code. It is a collection of name/value pairs usually stored in objects and arrays.
var ourObject = {
doSomething: function() {
(...)
},
'myString': 'foo',
myArray: ['foo','bar'],
myObject: {}
}

I have stored similar objects as before, however, even though I have stored them with the same names they will not over write the previous objects because they are stored with ourObject. They will render exactly the same results but will be called like so…
ourObject.doSomething()
ourObject.myArray(0)
// etc ...

Using this type of coding is much more efficient, and it’s considerably easier to read and understand because code is grouped into objects. It also allows you to use the same names for functions, for example ‘init’, which I use a lot.

Permalink 2 Comments