28
nov 09

Javascript Getters & Setters

K well this doesn't work in IE--shocking I know--however, it's pretty cool (the ActionScript folk will like it). You can have getter and setter properties in Javascript now. No need to have a winter.setSnow("Go Away") and winter.getSnow() style functions.

It's easy as pie:

Winter = function() {
  var privateStyleWinterStatus = "All the time";

  return {
    get snow: function() { return privateStyleWinterStatus; },
    set snow: function(val) { privateStyleWinterStatus = val; }
  };
};

// And now we can go like:

var winter = new Winter;
winter.snow = 'Go Away!';
console.log(winter.snow);

No I can hear the questions: "That's all fine and dandy, but what if already have an object?". Well that's a bit more cryptic, but good all the same (and you don't get stuck with the rigidity of ActionScript on this one):


var weather = function() {
  return ["blizzard", "clear", "light skiff", "freezing rain"][Math.round(Math.random() * 4)]
};

winter.__defineGetter__("weather", weather);

console.log(winter.weather);
console.log(winter.weather);
console.log(winter.weather);
console.log(winter.weather);