Saturday 16 November 2013

A nice Javascript idiom

At least, I think it's cute — type-purists would probably scream in horror. To my mind, it's illustrative in a very small way of the recent explosion in understanding of and familiarity with Javascript's amazing flexibility; it's gone from being despised s a mere web page scripting language to being recognised as a powerful and elegant multi-paradigm language with functional and metaprogramming elements in very short order.

Anyhoo, this is how to write a single function that not only acts as both a member getter and setter, but also allows you to chain setter calls:


radius: function(newRadius) {
if (arguments.length === 0) {
return this.r;
}
this.r = newRadius;
return this;
}

No comments:

Post a Comment