Practical example of need for prototypal inheritance

Neeraj Singh

By Neeraj Singh

on March 12, 2010

Alex Sexton wrote a wonderful article on how to use inheritance pattern to manage large piece of code. His code also has a practical need for prototypal inheritance for writing modular code.

Creating standard jQuery plugin

Given below is code that does exactly what Alex's code does.

1$(function () {
2  $.fn.speaker = function (options) {
3    if (this.length) {
4      return this.each(function () {
5        var defaultOptions = {
6          name: "No name",
7        };
8        options = $.extend({}, defaultOptions, options);
9
10        var $this = $(this);
11
12        $this.html("<p>" + options.name + "</p>");
13
14        var fn = {};
15        fn.speak = function (msg) {
16          $this.append("<p>" + msg + "</p>");
17        };
18
19        $.data(this, "speaker", fn);
20      });
21    }
22  };
23});

For smaller plugins this code is not too bad. However if the plugin is huge then it presents one big problem. The code for business problem and the code that deals with jQuery is all mixed in. What it means is that if tomorrow same functionality needs to be implemented for Prototype framework then it is not clear what part of code deals with framework and what part deals with business logic.

Separating business logic and framework code

Given below is code that separates business logic and framework code.

1var Speaker = function (opts, elem) {
2  this._build = function () {
3    this.$elem.html("<h1>" + options.name + "</h1>");
4  };
5
6  this.speak = function (msg) {
7    this.$elem.append("<p>" + msg + "</p>");
8  };
9
10  var defaultOptions = {
11    name: "No name",
12  };
13
14  var options = $.extend({}, defaultOptions, this.opts);
15
16  this.$elem = $(elem);
17
18  this._build();
19};
20
21$(function () {
22  $.fn.speaker = function (options) {
23    if (this.length) {
24      return this.each(function () {
25        var mySpeaker = new Speaker(options, this);
26        $.data(this, "speaker", mySpeaker);
27      });
28    }
29  };
30});

This code is an improvement over first iteration. However the whole business logic is captured inside a function. This code can be further improved by embracing object literal style of coding.

Final Improvement

Third and final iteration of the code is the code presented by Alex.

1var Speaker = {
2	init: function(options, elem) {
3		this.options = $.extend({},
4		this.options, options);
5
6		this.elem = elem;
7		this.$elem = $(elem);
8
9		this._build();
10	},
11	options: {
12		name: "No name"
13	},
14	_build: function() {
15		this.$elem.html('<h1>' + this.options.name + '</h1>');
16	},
17	speak: function(msg) {
18		this.$elem.append('<p>' + msg + '</p>');
19	}
20};
21
22// Make sure Object.create is available in the browser (for our prototypal inheritance)
23if (typeof Object.create !== 'function') {
24	Object.create = function(o) {
25		function F() {}
26		F.prototype = o;
27		return new F();
28	};
29}
30
31$(function() {
32	$.fn.speaker = function(options) {
33		if (this.length) {
34			return this.each(function() {
35				var mySpeaker = Object.create(Speaker);
36				mySpeaker.init(options, this);
37				$.data(this, 'speaker', mySpeaker);
38			});
39		}
40	};

Notice the Object.create pattern Alex used. The business logic code was converted from a function to a JavaScript object. However the problem is that you can't create a new on that object. And you need to create new object so that you could dole out new objects to each element. Object.create pattern comes to rescue.

This pattern takes a standard Object and returns an instance of a function. This function has the input object set as prototype. So you get a brand new object for each element and you get to have all your business logic in object literal way and not in a function. If you want to know more about prototypal inheritance then you can read more about it in previous blog .

Object.create is now part of ECMAScript 5 .

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.