One new pattern that I seem to now be using more and more is one I call Complex Assignments.
To introduce this, it is useful to look at simple assignment code first. An assignment is simply setting one thing equal to another:
var myVariable = 1;
this.myMember = "Some text";
this.myMethod = function() {
....
}
These are all simple assignments. Sometimes though this is not enough. Sometimes you need to set the value of a variable based on some parameter, eg:
function( myParam ) {
var myVariable;
if (myParam === 1) {
myVariable = "Some text";
} else {
myVariable = "Some other text";
}
}
Now of course this is a trivial example, but you may find yourself needing a more complex set of rules. In that case, the logic around this assignment can become complex. To alleviate this problem we will often delegate the assignment logic into a function. This is perfectly acceptable and actually desirable and in a JavaScript object we can make a private function to do the work:
function myObject() {
this.someValue = getSomeValue();
function getSomeValue() {
//do some work
.....
return someValue;
}
}
However, if this function is only going to get called once, there is no need to make it a named function. In fact I find it neater to make it an anonymous function. Of course, if its an anonymous function that only gets run once, we can make it a self invoking function. To rewrite the example above:
function myObject() {
this.someValue = (function() {
//do some work
.....
return someValue;
})();
}
In this instance, the code looks very similar (if somewhat neater). But, with this anonymous self invoked function, we are actually creating another level of scope which will get destroyed once the function has been executed. This can be very useful and can be very efficient. I also think the code is simple to understand and even better encapsulated.
This is particularly useful for the setting of constant like variables. I find myself using this pattern more and more as I find more occasions where I want a function to be used to assign a value to a variable.