Implementing super in JavaScript Sunday, Sep 21 2008 

The problem

JavaScript has objects and what is called prototypal inheritance, but it does not have built-in support for many features provided by other languages. In particular, it does not have built-in support for classes and instances. Nor does it have built-in support for methods of one class to call super-class methods.

Here is an example. Class C is a subclass of class B, and both have an init method. We would like the init method of Class C to be able to call the init method of class B. In other words, when writing init for class C, we wish to call the super-class init method. Note that class B might in fact be a subclass of class A, and that B might inherit init from A, and not have an init method of its own.

This post of focussed in the single topic of providing access to super-class. It does not for instance cover how to provide support for class hierarchies and how to manage instance creation.


Over the past few days I’ve been trying to understand John Resig‘s post on Simple JavaScript Inheritance, on both the technical and the practical levels. John’s goal was to extract the soul of the implementations of classical inheritance in base2 and Prototype, and to present them as a stand-alone package.

Well, I’ve not succeeded, but I do understand the problem better. In particular, I couldn’t get a clear understanding of what his _super method did. So to help me understand I set out to write my own. And this is what I came up with.

I hope in a later post to compare the two approaches. Be warned that this post is unavoidable quite technical, and that if you’re a JavaScript novice you’ll learn a lot if you manage to understand it all.


Data objects in JavaScript Saturday, Sep 20 2008 

The Problem

Suppose we want to count the words in a document, or the identifiers in a computer program. We’ll need to keep a dictionary (aka hash or mapping) whose keys are the words and whose values are their frequencies. When we come across a new word (or identifier) we add it to the dictionary as a key, with value equal to one. When we meet a word already in the dictionary, we increase the value by one.

The starting point, of course, is an empty dictionary (or mapping or hash or whatever you want to call it). In JavaScript creating one of these requires some thought, and seems not to have been done before. Here’s the problem. In JavaScript we have to store the data (key-value pairs) in an object, and every object comes with some builtin methods. Here’s some command-line JavaScript:

js> data = {};  // Create empty data object, we hope.
js> === undefined; // true
js> data['foo'] === undefined;  // true
js> data['constructor'] === undefined; // false - not what we want.