Friday, November 13th, 2009
Javascript Inheritance Patterns: Learning from Closure
The library portion of Google’s Closure not only gives us a new API to work with, but also adds another piece of mature code to the public domain, where it can be studied and scrutinized. Something we might normally have done with View Source if not for the compression techniques in effect.
A new article by Michael Bolin looks at inheritance patterns in Javascript, with a special focus on Closure. He does a thorough job of weighing up Closure’s use of the pseudoclassical inheritance pattern against what Doug Crockford labels the functional pattern.
Pseudoclassical inheritance (Closure):
- /**
- * @param {string} phoneNumber
- * @param {string=} signature
- * @constructor
- * @extends {Phone}
- */
- SmartPhone = function(phoneNumber, signature) {
- Phone.call(this, phoneNumber);
- /**
- * @type {string}
- * @private
- */
- this.signature_ = signature || 'sent from ' + this.getPhoneNumber();
- };
- goog.inherits(SmartPhone, Phone);
- /**
- * @param {string} emailAddress
- * @param {string} message
- */
- SmartPhone.prototype.sendEmail = function(emailAddress, message) {
- // Assume sendMessage() is globally available.
- sendMessage(emailAddress, message + '\n' + this.signature_);
- };
- /** @override */
- SmartPhone.prototype.getDescription() = function() {
- return SmartPhone.superClass_.getDescription.call(this) +
- ' It can also send email messages.';
- };
- var smartPhone = new SmartPhone('5555555', 'Adios'};
Functional inheritance:
- var smartPhone = function(spec) {
- var that = phone(spec);
- spec.signature = spec.signature || "sent from " + that.getPhoneNumber();
- that.sendEmail = function(emailAddress, message) {
- // Assume sendMessage() is globally available.
- sendMessage(emailAddress, message + "\n" + spec.signature);
- };
- var super_getDescription = that.superior("getDescription");
- that.getDescription = function() {
- return super_getDescription() + " It can also send email messages.";
- };
- return that;
- };
- var mySmartPhone = smartPhone({"phoneNumber": "5555555", "signature": "Adios"};





I like the arguments that are made here, but there is one major important factor that is missed. With closure, your using a lot of sugar from a library to make things work – you need to be aware of how a third party will manage versions of their library and as well its compiler. With the functional example, your using pure javascript. So this really becomes an argument of what tool is better for the job. Highly complex project (IE google maps)? Perhaps Closure will benefit you.
Great Post! I am really interested in Google Closure Tools and wrote a few articles based on my experience. You may check the following article to understand how well Closure Compiler works: Google Closure Compiler vs. YUI Compressor – Comparing the Javascript Compression Tools