Saturday, 19 January 2013

Interesting Object Initialization Trick

One of the reasons why I love JavaScript as a language so much is because you constantly find awesome tricks that make you exercise your brain. Some months ago I wrote here about how to circumvent the limitations of Object literals when it comes to initializing a field based on other fields.

var foo = {
   a: 5,
   b: 6,
   init: function() {
       this.c = this.a + this.b;
       delete this.init; //do this to keep the foo object "clean"
 return this;
   }
}.init();

I was quite happy with the solution that I copy-pasted there, but today just by chance I've come across another interesting one, that has the advantage that it will most certainly make the eyes of whoever reads your code blink quite a few times :-D

The technique discussed here:

var o = new function() {
    this.num = Math.random();
    this.isLow = this.num < .5; // you couldn't reference num with literal syntax
}();

It makes a very intelligent use of what we could call "anonymous constructors" or "temporal constructor" as the author says.

No comments:

Post a Comment