Exploring JavaScript prototypes via TypeScript’s class pattern

Note: All the diagrams below were created using Gliffy, a fantastic web-based diagram editor. The latest version has been rebuilt using HTML and JS instead of Flash, and it really is a joy to use.

In this post, I’m going to take a close look at how JavaScript’s prototypal inheritance works by analysing how Microsoft’s TypeScript language uses it to provide a simple implementation of classes. Don’t worry if you’ve never used TypeScript, we’re not really concerned with the language itself here, just the JavaScript that is produced by its compiler, and how it achieves class-based inheritance in a language that doesn’t natively support it.

This is of particular importance because EcmaScript 6 will include classes that work a lot like TypeScript’s. The idea of adding classes to JavaScript is controversial, but I think some of the hostility stems from a mistaken belief that classes are some kind of competing inheritance mechanism to prototyping, or are an attempt to turn JavaScript into Java. In fact, modern proposals for classes in JavaScript are just a syntactic codification of prototypal inheritance patterns that are already in use.

I’m going to copy the approach Joost Diepenmaat used in his excellent article Constructors Considered Mildly Confusing,  by providing diagrams to illustrate the actual objects, properties and relationships that result from particular code statements. Incidentally, if you haven’t read Joost’s article, I recommend you do so. If you’re like me, and have frequently muddled through JS prototyping like it’s a JobInterviewQuicksort, then it’s a great introduction to how everything actually works under the hood.

The TypeScript Code

In case you’re unfamiliar with it, TypeScript is Microsoft’s entry into the crowded altJS language space, also occupied by the likes of CoffeeScript, Dart, Objective-J, and a wealth of others. TypeScript seems to stick closer to the EcmaScript 6 vision of JavaScript.next than most of the others, while also adding features like static typing and generics that will, depending on your prejudices, either enable sophisticated, grown-up programming on the web, or placate .NET developers too scared to use a dynamic language ;-). Perhaps it’s my many years spent coding with C#, but TypeScript feels a little more pleasant to me than Dart (although they share a lot of similarities).

Like many of these “transpiled” languages, the TypeScript site has an interactive playground where you can write some TypeScript code on one side of the screen and see the equivalent compiled JavaScript on the other. One of the provided examples demonstrates TypeScript’s class inheritance. If you’ve ever wrangled with Microsoft’s ASP.NET Ajax Library type system and its mechanisms for class and namespace registration and inheritance, you might be a little apprehensive here, but what TypeScript provides is much simpler, embedding a simple extension mechanism that builds on JavaScript’s standard prototypal inheritance.

Let’s briefly look at the original TypeScript code:

class Animal {
    constructor(public name: string) { }
    move(meters: number) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    move() {
        alert("Slithering...");
        super.move(5);
    }
}

class Horse extends Animal {
    constructor(name: string) { super(name); }
    move() {
        alert("Galloping...");
        super.move(45);
    }
}

var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);

This should be easy to follow, even if you’ve never seen TypeScript before. It declares a base-class Animal with a constructor and a move instance method, and two classes, Snake and Horse that inherit from it. The inheriting classes have their own constructors, which call the superclass constructor. They also provide overriding implementations of the move method that also call the corresponding superclass method.

The Compiled JavaScript

Here is the the same code after being compiled into JavaScript by the TypeScript compiler:

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};

var Animal = (function () {
    function Animal(name) {
        this.name = name;
    }
    Animal.prototype.move = function (meters) {
        alert(this.name + " moved " + meters + "m.");
    };
    return Animal;
})();

var Snake = (function (_super) {
    __extends(Snake, _super);
    function Snake(name) {
        _super.call(this, name);
    }
    Snake.prototype.move = function () {
        alert("Slithering...");
        _super.prototype.move.call(this, 5);
    };
    return Snake;
})(Animal);

var Horse = (function (_super) {
    __extends(Horse, _super);
    function Horse(name) {
        _super.call(this, name);
    }
    Horse.prototype.move = function () {
        alert("Galloping...");
        _super.prototype.move.call(this, 45);
    };
    return Horse;
})(Animal);

var sam = new Snake("Sammy the Python");
var tom = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);

The code has roughly the same shape as the TypeScript code, but there is a bit more going on. The class definitions have been replaced with immediately-invoked anonymous functions, and a new function __extends has been inserted at the top. This function may only be four lines long, but it is the key to TypeScript’s implementation of class inheritance.

Basic Function Declarations

Let’s step through the code section by section, as if it were executing, and visualise exactly what’s happening with diagrams.

The first thing that happens is that the __extends function is declared and defined, if it has not already been defined elsewhere by some other compiled TypeScript code. We can ignore the actual contents of this function for now, and use a diagram to explore what a function declaration such as this one actually corresponds to behind the scenes.

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};

extends

Note: These diagrams can be interpreted as follows: Every ellipse represents an object. Yellow ellipses are regular objects, whereas the blue ellipses with names ending in parentheses are function objects. Arrow connections represent properties of an object, where the connection’s label is the property name, the arrow points from the object to which the property belongs, to the object referenced by the property. For example, in the diagram below, the __extends function object has a property named prototype that references the __extends.prototype object.

Properties with a solid purple connection are regular JavaScript properties. The kind you can access using the dot or square-bracket syntax in  JS code. Properties with a dotted green connection are internal properties, belonging to the runtime. They cannot be accessed directly by code ([[Prototype]] can accessed indirectly through other methods in some JavaScript runtimes, but that’s beyond the scope of this discussion).

Here we see that __extends is a function object, whose internal [[Prototype]] property points to Function.prototype, which in turn has a [[Prototype]] property pointing to Object.prototype. The __extends function object also has a regular property called prototype that references an object we’ll call __extends.prototype. This object has a property called constructor that references the __extends function object. Neither the prototype or constructor properties are internal like [[Prototype]]. They are regular JavaScript properties and can be accessed in code and overwritten, as we shall see.

The code didn’t explicitly create the __extends.prototype object or set these properties. Rather, the JavaScript runtime set it all up automatically, as it does for every function declaration. This is why every JavaScript function can be used as a constructor with the new operator. Although it’s not intended to be a constructor, it is possible to call new on __extends. The result would be a new object whose [[Prototype]] property pointed to __extends.prototype.

This can all be a bit of a headache at first, but grasping the difference between the constructor function, its prototype property, the referenced prototype object, and the internal [[Prototype]] property is vital to really understanding inheritance in JavaScript. It is the next step beyond just reusing the standard prototype and closure patterns to create objects.

Class Definitions

Moving on, the next part of the code to execute will be the declaration of Animal

var Animal = (function () {
    function Animal(name) {
        this.name = name;
    }
    Animal.prototype.move = function (meters) {
        alert(this.name + " moved " + meters + "m.");
    };
    return Animal;
})();

Because Animal is a base-class within TypeScript, it doesn’t make use of the __extends function. Instead, we can see that it has been compiled into a pretty standard prototype pattern declaration, which is returned as the result of an immediately-invoked anonymous function and assigned to variable. The only possibly confusing thing is the duplication of the name Animal for both the function inside the anonymous function and the variable in the parent scope. Every use of Animal within the anonymous function references the function declaration, whereas every use outside references the variable that gets assigned to the result of the anonymous function. However, since the former is what gets assigned to the latter, it makes no practical difference.

Of course, although it doesn’t use TypeScript’s inheritance, Animal and the objects created by new-ing it will still participate in standard JavaScript inheritance. By default, objects in JavaScript have a [[Prototype]] chain leading to Object.prototype. The end result will be very similar to the __extends declaration I depicted above, except that in this case the Animal function is intended for use as a constructor with the new operator.

Animal

The only difference between this layout and __extends‘s is that the Animal.prototype object has a move property, and that property is assigned to a function object (which, of course, is also an object, and has an internal [[Prototype]] property referencing Function.prototype.)

Class Instances

The Animal class isn’t used directly, but what if it was? Imagine the next line of code was as follows…

var jim = new Animal("Jim the Possum");

Here we’ve new-ed an instance of Animal assigned to a variable called jim. What would this give us?

jim

To avoid overcomplicating the diagram, I’ve removed some of the unimportant [[Prototype]] links and the Function.prototype object, but in reality they would still be there. Instead, let’s concentrate on what’s happening with the jim variable: It is an object, whose internal [[Prototype]] property points to Animal.prototype, and therefore it will inherit the properties of that object, namely the move property and its associated function. Calling jim.move() will execute Animal.prototype.move, unless we have overridden it by setting a move property on the jim object itself.

Class Inheritance

OK, so this is all pretty standard stuff, but now things get more interesting, as execution reaches the declaration of the Snake class, which is as follows:

var Snake = (function (_super) {
    __extends(Snake, _super);
    function Snake(name) {
        _super.call(this, name);
    }
    Snake.prototype.move = function () {
        alert("Slithering...");
        _super.prototype.move.call(this, 5);
    };
    return Snake;
})(Animal);

Again we have an immediately-invoked anonymous function, but this time it takes a single argument, Animal. This argument is referred to as _super within the anonymous function body. Leaving aside the __extends call for a second, we can see that the body of the anonymous function contains another prototypal declaration, similar to that of the Animal declaration above. If we compare the code with the original TypeScript, we can see that the calls to the superclass, which used the super keyword in TypeScript, have been compiled to use the _super argument.

For Snake, _super references the superclass constructor Animal, and _super.prototype property references the Animal.prototype object. The Snake class can access the behaviour of its superclass by call-ing its constructor and its prototype methods and passing in the this reference, which will execute the functions in the context of the subclass instance.

Now, what about that __extends call? Although it appears first in the anonymous function body, the Snake function declaration will be hoisted above it by the runtime. Therefore __extends will execute after Snake is declared, but before anything is assigned to Snake.prototype, giving it an opportunity to modify that property first. It is called with two arguments, the Snake function and the _super object.

As we saw earlier, the code for the __extends function is quite terse, so here’s a slightly expanded version that might be easier to parse:

var __extends = this.__extends || function (subclass, superclass) {
    for (var propertyName in superclass) {
        if (superclass.hasOwnProperty(propertyName)) {
            subclass[propertyName] = superclass[propertyName];
        }
    }

    function subclassPrototype() { this.constructor = subclass; }
    subclassPrototype.prototype = superclass.prototype;
    var newPrototype = new subclassPrototype();
    subclass.prototype = newPrototype;
};

The first thing the function does is to loop through every enumerable property of the superclass and copy it to the subclass. Note that it is the properties of the superclass constructor function that are copied, not those of its prototype. TypeScript likely does this to allow subclasses to access “static” members of their superclass.

The next four statements are the trickiest part. As we saw earlier, the runtime will have created a default prototype object for the subclass function, with its [[Prototype]] property referencing object.prototype. In order to allow instances of the subclass to inherit the superclass properties, the extension mechanism needs to create a replacement prototype object whose [[Prototype]] property points to the superclass prototype. Lets go through the statements one by one.

function subclassPrototype() { this.constructor = subclass; }

First, there is a function declared, which I have renamed subclassPrototype. As before, a regular function declaration like this will result in a function object and an automatically created prototype object with a [[Prototype]] chain pointing to object.prototype.

subclassPrototype

Next the prototype property of the subclassPrototype function is assigned to the superclass’s prototype object.

subclassPrototype.prototype = superclass.prototype;

subclassPrototype2

The constructor property of the automatically generated prototype object is still pointing to subclassPrototype, but that won’t have any effect, and we can forget about subclassPrototype.prototype from now on.

var newPrototype = new subclassPrototype();

Next we declare a new variable newPrototype and assign it to a new-ed up instance of subclassPrototype. It’s important to understand what happens here. Calling new on a function triggers the following process within the runtime:

  1. A new object is created.
  2. The new object’s internal [[Prototype]] property is assigned to the value of the constructor function’s regular prototype property.
  3. The constructor function is executed in the context of the new object. E.g. within the function, the this keyword will be bound to the new object.
  4. The new object is returned as the result of the whole new subclassPrototype() expression.

This process will result in an object newPrototype whose [[Prototype]] property points to the superclass prototype. This means it will inherit the constructor property from the superclass prototype, but because this prototype is intended for the subclass, that is not correct. The constructor property for newPrototype should reference the subclass function, therefore subclassPrototype reassigns it within the constructor function. The end result is an arrangement as follows:

newPrototype

We now have a newPrototype object with the correct [[Prototype]] chain, and the correct value for constructor.

subclass.prototype = newPrototype;

The final step is just to reassign the prototype property of subclass to the newPrototype object. This takes the default subclass.prototype object out of the picture leaving us with the following arrangement:

newPrototype2

And this is exactly what we want. From now on, new-ing an object with the subclass function will result in an object whose internal [[Prototype]] property points to newPrototype, which in turn allows it to inherit from the superclass prototype and also gives its a constructor property that points back to the subclass function.

The Class Hierarchy

At this point, the __extends function finishes executing, and control passes back to Snake‘s anonymous function. The code can then proceed to add properties to Snake.prototype, which will now reference the correctly configured prototype object that __extends created.

The Snake class declaration is followed by the Horse class declaration, which works identically. When all three classes have been declared, the result will be a prototype hierarchy where Horse.prototype and Snake.prototype both inherit from Animal.prototype, which in turn inherits from Object.prototype, as illustrated.

snakes-horses-oh-my

Using Classes

From then on, things are straightforward. Instances of Horse and Snake are new-ed up and assigned to variables in the usual way, then their instance methods are called.

var sam = new Snake("Sammy the Python");
var tom = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);

Based on everything we’ve gone through so far, hopefully the prototype hierarchy for the object instances should be fairly obvious:

sam-and-tom

Accessing properties of the sam and tom objects acts we would expect. Since neither object has its own property called move, the JavaScript runtime looks up the [[Prototype]] chain for a match. The move functions referenced by Snake.prototype and Horse.prototype will be found first, and therefore hide the move function defined on Animal.prototype. However, the use of the _super object within the definitions of those functions means that the Animal implementation of move is still run.

Wrapping Up

Hopefully all that was reasonably intelligible and will be of use to some people. Doing worked examples like this is an excellent way to get a stronger grasp on an area of JavaScript that can be fuzzily understood if you spend most of your time writing code that consumes frameworks and doesn’t mess around with prototypes too much.

As with any technical article like this, there are likely errors and things I’ve misunderstood. Please let me know of any problems via the comments.

Game of Thrones: The Rains of Castamere

Warning! Here be spoilers for the Game of Thrones episode “The Rains of Castamere”, and also for the books.

There is an existential bleakness and cynicism at the heart of George Martin’s Song of Ice and Fire books that often makes them hard to take. As a reader, you can fall in love with them, but sometimes it feels more like falling into an abyss, as they steadfastly refuse to return your love with anything in the way of hope, romance or joy. The big, set-piece deaths, of characters like Ned Stark, and the events of the Red Wedding, are the most famous examples of Martin’s unflinching brutality, but while these are huge shocks in the narrative, their contribution towards the tone is surpassed by the many small cuts of equally bleak, but smaller moments. Mistakes, misunderstandings, lies, accidents, abuse, assaults, maimings and murders are the constant currency of the books and their culmulative effect is one of slow dawning, depressive horror.

What makes it possible to bear the books, even to love them, is two things: The first is the barest traces of light that Martin allows to infiltrate his work. The characters of Jon Snow, Arya Stark, and Tyrion Lannister endure terrible things, but their respective honour, vitality, and wit provides a small candle amid all the darkness that the reader can hold on to, even if they are all the while wondering when Martin will snuff it out, that stops the books from turning into an unbearable slog. It’s no surprise that when the books’ focus shifts away from these characters, to others like the Martells, that they tend to suffer. The second thing is the sheer richness of the world and its mythology. The endless details of long dead lords and kings, myths, stories and past wars can be overwhelming, but they also help make Westeros more than just a killing field, into an edifice of the imagination. The richness of the language and descriptions of pageantry, landscape and feasting make the barbarity easier to swallow. It’s like a masterful painting of a scene of carnage, the technique can’t disguise the horror, but its skill can make it more palatable.

The TV series makes the story bearable in similar and different ways. One way is by filing off the roughest edges of the story. While the adaptation retains the biggest, darkest beats of the story, the murders and the maimings of the protagonists, lesser ones are skipped, reduced or simply hinted at. Arya in the books, for example, witnesses appalling horrors when she encounters Gregor Clegane’s reaving of the riverlands, and her response is dark and violent. The TV show follows the broad strokes, but the details are nowhere near as nasty. In the books, Tyrion is horribly maimed at the Battle of Blackwater Bay, with most of his nose being cut away. In the TV show, Tyrion is injured in similar circumstances, but only ends up with a badass battle scar. And all throughout, humour and levity are allowed to seep into many scenes and characters were it was absent in the book. Partly this is the show’s writing, which maintains a brisker, lighter and more modern tone than the books, and partly it is the actors. Jerome Flynn and Peter Dinklage can instill a sense of humanity, black humour and shared camaraderie in their characters that a dozen pages of prose could not replicate.

The TV show also redeems the bleakness through the richness of its detail, although in this case the detail can be seen and heard, not just read about and imagined. Many die hard fans of the book will always dislike the adaptations because they make concrete, and therefore limited, what previously only existed in those fans imaginations. And if the real thing doesn’t match or live up to the imagined version, then it can be a let down. But this is not always the case. At its best a TV show or a movie can give you something better than you could have ever imagined yourself. A combination of the best actors, writers, set and costume designers, directors and editors produce something that acts as a window into a collective, gestalt imagination. Reading a book and fantasizing about its story and characters can help to strengthen your imagination, but perhaps also seeing how that book is interpreted through the collective imagination of others can help to teach your imagination better and more intricate ways to conceive of things. Perhaps a mixture of both is the best medicine for a healthy mind.

Because the TV files off some of those hard edges and lets more light into the scene, it also means the moments of true darkness -and they don’t come much darker than the Red Wedding, as it is referred to, in the episode the Rains of Castamere- tend to hit that much harder. They are an unwelcome intrusion of brutal reality into what otherwise hews a little more closely to a conventional narrative. These beats, the death of the hero, followed by the death of his avenging son are doubly shocking, because not only are they ugly, violent events within the context of the story, but they also upend conventions of narrative they viewers, and readers, unconsciously rely on. This is, of course, an entirely intentional effect, as testified to by George Martin himself, but it also has the effect of pissing off a lot of viewers, as some of the online reaction to the latest TV episode attests. Some have responded with a stream of invectives aimed at HBO, the show’s producers, and Martin himself. Others have threatened to boycott watching the show, much as they did after Ned’s death in season 1.

It’s easy as a ready of the book to roll your eyes at this kind of reaction, but while it may be over the top, it’s important to recognise that it stems from understandable sources, particularly the way most people are conditioned to expect certain tropes and established patterns to occur in fiction. Noble protagonists dying horrible, bloody deaths surrounded by the corpses of their family and friends are not a common event in fiction. We book readers may have become somewhat inured to their effect within Game of Thrones/A Song of Ice and Fire, firstly due to the longer time we’ve had to process them since we first read them, but also because the remorseless bleakness mentioned above gradually adjusts your attitude to the narrative, until your expectations are better aligned with how Martin does things. After such an adjustment, it’s easy to laugh at those who haven’t, or won’t, adjust their expectations accordingly, but we shouldn’t forget that our original reactions probably weren’t much different.

An interesting question arises, why is A Song of Ice and Fair bleaker and brutal than many equivalent stories in its genre; enough to confound the expectations of at least some of its audience and inspire such strong reactions? You could just say, it’s because that’s just Martin’s temperament, but that doesn’t really get you anywhere. Why is his style different? I can’t say for sure, but if I had to hazard a guess it would be the greater influence of history over Martin and his writing, than other writers. My theory is as follows: Most fiction is shaped by the writer’s own reading, and by their environment. A writer from a difficult background, perhaps containing poverty, violence and abuse, is likely to write darker material than a writer from a happy or contented background. Most modern western writers have the happy privilege of living within societies that are on the whole more peaceful, healthier and more plentiful than any others that have existed in history, and this is reflected in their writing. Even those whose writing features heavier material, inevitably tend to place it within a framework that has some degree of hope and positivity. Furthermore, over time all the stories written by these authors has formed into a shared corpus that serves as the second great influence over new writing, which itself becomes part of the corpus. In this way, the tropes and idioms of fiction are established, and become expected by both writers and readers alike.

Where Martin differs from many of his contemporaries, perhaps, is that an additional, primary source of influence on A Song of Ice and Fire is historical record. Studying and reading history tends to inspire a very different view of human nature than that which follows from narrowly observing western society and fiction. The current peace and stability enjoyed by some in the modern world, becomes not the default state, but a tiny cap on an otherwise bloody and horrible history, replete with famine, war and genocide. The capacity of historical peoples, particularly their rulers, for torture, slaughter, and pointless cruelty is staggering. There are few events in A Song of Ice and Fire, including the Red Wedding, that don’t have some equivalent historical event lurking in the background. Those events are magnified and modified through the lens of fantasy and Martin’s imagination, but the original brutality is retained. The fact that the narrative has such a basis in real history is probably the best defense against charges of sadism that Martin occasionally faces. If every terrible act he wrought upon his characters as purely the product of his fervid imagination, then you might well worry about him. But by reflecting what humanity has already done to itself, Martin should make you worry less about him and more about all people, and your self. In the right circumstances, are you, or any of the people you know, capable of the barbarity displayed in these novels?

The unflinching brutality is both the novels most difficult aspect, and its most important. For all its fantasy trappings, A Song of Ice and Fire tells a story far more true to life than many more conventional books. Tasha Robinson at The AV Club also posted an excellent analysis of the Red Wedding’s impact, and includes an interesting theory on Martin as a romantic writer, despite his cynicism. It chimes with what I’ve noticed in his work, that there are certain lines he won’t cross, even with all the abuse he heaps upon his characters, that help separate it from horror porn. Many of the escapes from death, torture and rape that characters like Bran, Rickon, Arya and Sansa manage are actually rather unlikely, given the establish facts of his world, but Martin doesn’t seem willing to hurt them that badly. They’re not unscathed, by any means, but what mercy they are shown hints at some hope for their survival and even happiness, before the novels reach their end.

Game of Thrones: The Bear and the Maiden Fair

It’s always fascinating to watch an episode of Game of Thrones written by George R R Martin. The show has departed from the source novels in a lot of ways, mostly small, occasionally large. Often it’s a matter of necessity, as a completely faithful adaptation would require ten times the episode count and a thousand times the budget, and probably wouldn’t make great television anyway. The written word and the small screen are very different mediums, and you need to tailor a story to fit each. But it’s still strange to imagine Martin sitting there, working on a screenplay, constrained by changes others made to a plot he originally wrote himself in a different way.

You might wonder if Martin would chafe under the requirement to alter his vision, or if his episodes would try to move things closer to the books, but if anything he seems to positively embrace the changes. For every line or scene from the book in his episodes, there’s a dozen or more that are entirely new, and while his dialog perhaps carries a little more of the lyricism and formalness of the novels, he by no means abandons the lighter, more modern tone of the rest of the series.

The Bear and the Maiden fair contained a fascinating example of Martin reinterpreting his own work in the discussion Sansa and Margaery had about Tyrion, to whom Sansa is now engaged. There was a particular line, in which Margaery says Tyrion is handsome, despite, or even because of, his scar. This line took me by surprise a little, not because it’s untrue: Peter Dinklage is certainly a handsome man, but because it states openly what was previously a major, but unacknowledged departure from the books: Tyrion’s ugliness.

The books are quite clear on Tyrion’s ugliness. He is not simply a dwarf, he is extremely ugly, almost monstrous. Then the wound he receives during the battle for Kings Landing results in half his nose being cut away, leaving him even more hideous. This ugliness is remarked upon by many characters, including Tyrion himself. In the TV series, Tyrion is not ugly. He is a dwarf, yes, and he less conventionally handsome that other men, but he is far from ugly. Unless, like Sansa, you find dwarfs inherently unattractive, then it would be difficult not to acknowledge that Tyrion is in his own way another handsome member of a handsome family. In that respect, the TV series has departed from what is quite a significant aspect of the novels.

Here the problem though: Tyrion not being ugly makes some of the story rather problematic. In the books, Tyrion’s appearance inspires such instinctive dislike that he it makes him a constant outsider, loathed by the peasantry and the high born alike, and protected only by his family name. He frequents whores because other women won’t consider sleeping with him, and is unmarried because only the most desperate lords would consent to him making a match with their daughter. This is despite him being one of the cleverest, richest, and kindest characters in the novel. Tyrion’s story is an indictment of the way people judge by appearance, and willing blind themselves to the truth in order to maintain their pre-judgements. They see a monster, so they want to believe he is a monster.

It’s not clear why the Tyrion of the TV series would be such an outsider or inspire such loathing. He’s just as clever, just as rich, and just as kind, but he’s also older, and handsome. Even accepting that the society depicted has a greater prejudice against dwarfs than our own, is it really believable that Tyrion would be unable to find women outside of whorehouses? Or that no high born lady would fall for his charms, or that her father would consent to her marrying the heir to the Lannister lands, title and wealth? I’m not sure it is.

Don’t get me wrong: I think Peter Dinklage is fantastic, and I wouldn’t want any other actor in the role, even if they were closer to the Tyrion as described in the book, but I thought it was interesting, particularly since George Martin seemed to deliberately hang a hat on in in this episode. It’s interesting as well that he also decided to make Sansa openly state that her dislike of Tyrion basically comes down to him being a dwarf. Sansa is already far from the most sympathetic character, and this isn’t likely to endear her to people any more.