Wednesday, October 31st, 2007
Transitioning from Java Classes to JavaScript Prototypes
To class or not to class, that has been a question than many developers have faced as they came from class based OO worlds into the Prototype Oriented world of JavaScript. Much pain has endured for those that try to contort it.
Peter Michaux has detailed transitioning from Java Classes to JavaScript prototypes by looking at the Observer/Observable pattern and showing various implementations in Java and JavaScript ending up with his favourite mixin-able solution:
-
-
var observablize;
-
-
(function() {
-
-
var observable = {
-
-
addObserver: function(observer) {
-
if (!this.observers) {
-
this.observers = [];
-
}
-
this.observers.push(observer);
-
},
-
-
notifyObservers: function() {
-
for (var i=0; i<this.observers.length; i++) {
-
this.observers[i].update();
-
}
-
}
-
-
};
-
-
observablize = function (subject) {
-
for (var p in observable) {
-
subject[p] = observable[p];
-
}
-
}
-
-
})();
-
-
// ---------------------------
-
-
function WeatherModel() {}
-
-
observablize(WeatherModel.prototype);
-
-
WeatherModel.prototype.setTemperature = function(temp) {
-
this.temp = temp;
-
this.notifyObservers();
-
};
-
-
WeatherModel.prototype.getTemperature = function() {
-
return this.temp;
-
};
-
-
// ---------------------------
-
-
function CurrentConditionsView(model) {
-
this.model = model;
-
model.addObserver(this);
-
}
-
-
CurrentConditionsView.prototype.update = function() {
-
alert(this.model.getTemperature());
-
};
-
-
// ---------------------------
-
-
var victoriaWeather = new WeatherModel();
-
var victoriaNews = new CurrentConditionsView(victoriaWeather);
-
-
victoriaWeather.setTemperature(15.3);
-
victoriaWeather.setTemperature(17.0);
-
victoriaWeather.setTemperature(14.7);
-












Sadly, the basic premise of the article, “simulating class-based inheritance in JavaScript really doesn’t work” is no longer true. Prototype 1.6 features a rather elegant solution to this problem in the form of the “$super” argument (see http://prototypejs.org/2007/8/15/prototype-1-6-0-release-candidate for details).
The mixin and observable patterns are still useful, but no longer essential workarounds where true inheritance is required.