Inheritance and Javascript

Time for a technical post.

Javascript is a ‘prototype’ based language, and it means that inheritance is a different animal in Javascript than it is to more normal object oriented languages. You’ll see a million different ways of doing what seems a very standard thing. There are quite a few inheritance patterns that I’ve found on the web, often even using large and complex libraries.

The commonly seen inheritance pattern (even in impressive reference tomes) is this:


function Parent( args ) {
// set up stuff
}
Parent.prototype.someMethod = function() { /* Do some work */ }
function Child( args ) {
// call the parents constructor with args
// then set up your own stuff.
}
Child.prototype = new Parent();
Child.prototype.someMethod = function() { /* Do some work */ }

This works, in that the prototype chain is set up and attributes and methods are inherited. Where it doesn’t work is that you had to construct a new Parent at the time of the Childs definition rather than instantiation. Often the parents constructor simply doesn’t make sense taken in isolation like this, besides the frustration of having to call it again when the child is instantiated.

One suggestion was to set the prototype of the Child to the prototype of the parent.


function Parent( args ) {
// set up stuff
}
Parent.prototype.someMethod = function() { /* Do some work */ }
function Child( args ) {
// call the parents constructor with args
// then set up your own stuff.
}
Child.prototype = Parent.prototype;
Child.prototype.someMethod = function() { /* Do some work */ }

But this doesn’t work because the prototypes are shared and the parents someMethod is corrupted by the client overriding it. But playing around the other day, we worked out a sneaky way around this, you can create an empty object which inherits from your parents prototype, and then inherit from that.

function Parent() { }
Parent.classconstructor = function() { /* An object to represent the class */ }
Parent.prototype = new Parent.classconstructor();
Parent.prototype.someMethod = function() { /* Do some work */ }
function Child() { }
Child.classconstructor = function() { /* An object to represent the class */ }
Child.classconstructor.prototype = Parent.prototype;
Child.prototype = new Child.classconstructor();
Child.prototype.someMethod = function() { /* Do some work */ }

A bit confusing maybe, but the inheritance chain is perfect, you don’t corrupt your parents prototypes when you assign methods to the Childs prototype.

You can wrap all this up into a utility method quite easily, which then doesn’t pollute your namespace.


function extend(clazz, superclass) {
	var intermediate = function() {};
	intermediate.prototype = superclass.prototype;
	clazz.prototype = new intermediate();
	// you can do other stuff here to set up
	// for example easy ways to call your super constructor,
	// or super methods, or convenient ways of finding
	// your own constructor.
}

and then you can use it very easily.


function Child() { }
extend ( Child, Parent );
Child.prototype.someMethod = function() { /* Do some work */ }

So, all you javascript geniuses out there on the internet, let me know – is this a good pattern, or are there hidden dangers?

Permanent Serendipity

And we know that all things work together for good to those who love God
Romans 8:28

The Church of Logitech was an enormous building, built of huge stone blocks with buttresses plunging great depths into the water on all sides. Antony stood in his dirty suit at the end of the bridge, with his hand on the door. The huge dark oak doors were closed, but there was a smaller entrance cut out of the right hand door that was open. Even knowing that it’d been built with some of his money, it was hard not to be intimidated. He breathed deeply, summoned up his outrage, and pushed on the door.

Inside, huge marble pillars soared up to the gold inlaid dome. Specks of dust and smoke from the incense sticks danced in the few shafts of light. Antony was halfway down the marble aisle towards the sanctuary before he was met by an hooded and cloaked figure.

“Hi, I’m Steve, and I’m your pastor for this evening”

Antony sighed. “I’d like to speak to the abbot of customer services.”

Steve looked Antony up and down, taking in the dishelved hair, the stubble, the scent of alcohol, and the thorougly disheveled suit. He’d only been working here three weeks, but he was getting quite good at evaluating peoples need and potential for being blessed. Working here had been the cheapest way for him to acheive his own blessing.

“I’m afraid he’s busy, you could make an appointment for two months time.”

“Pastor eh? New though. I bet you aren’t even given 5 minutes of grace processing to pass to the worshipers. I’m not here for blessing, I am the owner of the Most High Prioirty.”

The claim seemed unlikely, but Steve gazed up at the row of icons depicting the blessed along the ceiling. The man before him was there, unmistakable even in mosaic. Flustered, he bowed and said “Of course, please follow me sir”.

The abbot of customer services was dining with the abbot of the exchequer, discussing money and clerical matters over fine food, but when he saw Antony, he excused himself immediately.

They sat together in a confessionary where poorer folks could swap information about their doings out of the eye of society for a brief blessing. He knew that everything would be recorded by the serengents, but it was in strictest confidence – nobody could talk to a serengent.

“Why are you even here? You have already received the greatest blessing we can give you, you have no need for worship – there is no point entering you in the worshipers lottery for greater priority, you already have the Most High Priority, you are more blessed (he pronounced the ‘ed’) than the Bishop of Logitech himself”.

“I want to talk to my serengent.”

The abbot spluttered as if he was still eating the fine duck he’d left behind. “Impossible. I don’t care if you are the richest man in the world and the owner of the Most High, no one may speak to their serengent”.

“Was the richest man in the world. In the time since I was ‘blessed’, my wife has left me, my businesses have gone under, my new house collapsed, and the nicest members of my family have died, the rest have fallen on hard times.”

“Strange, strange, indeed, but we never promised you that life would be easy afterwards, just easier than it would otherwise have been. Whatever may have gone wrong, you must trust that you are living the best possible life.”

Antony snorted “I no longer believe. My life is harder than ever before, and I see no changes to the benefit, just an invisible malevolent hand conspiring against me.”,

“Blasphemy! Your serengent is calculating all the possibilities, and making tiny, subtle changes in thousands of situations across the world. It can change information systems, weather systems, traffic systems all across the world. It is supernetral. It can make sure information comes out, or is buried. It knows so much about every individual that it can direct the course of their actions by simply changing the art on the wall, or by altering the scent in the air conditioning. It is a perfectly benign, all powerful software agent, dedicated to your benefit and that alone. You must know that whatever is happening is part of a plan, being woven together as a tapestry by the most sophisticated intelligence known to man. It understands far more than you, it knows every person, place and thing on this planet intimately. Unlike everyone else on the planet, you have an unconstrained serengent. It makes changes for your benefit without concern for the plans of others. Whatever has happened in your life since you were blessed is for the best.”

“I have heard stories”, Antony said, “stories of serengents created to inconveience people, to make their life harder. A curse. On the streets, I met a woman who swore that she had been cursed by one of your exinitiates.”

The abbot became a little more red faced. “It has happened,” he said hesitantly, “our deifiers must create curses to test the blessings against, but they are kept locked up in the crypt, only one has ever become supernetral, and we hunted it down and punished the initiate who released it.

“Perhaps you cursed me instead of blessing me.”

“There is no way that that could happen. We are very careful, and besides, a curse with Most High priority would certainly have found a way to kill you by now.”

“This is wrong you know. You are controlling peoples lives. You are destroying their free will. You have created a false God”

It was the abbots turn to snort contemptuously. “You had no trouble with it when you believed that peoples lives would be controlled for your benefit”. He paused for Antonys rebuttal, but Antony could say nothing. He knew the abbot was right. “As for ‘false God’, it has always been mankinds aim to create God, first in the imagination, then in craftsmanship. Now finally, with the benefit of modern technology, we have succeeded. Replacing supernetral for supernatural, we have finally created the all loving, all powerful, all knowing intelligence, and we make it available at a very reasonable cost. Primitive beliefs in primitive Gods have faded quickly as the whole world has seen the immediate benefits of worshiping here. We are the most successful religion that has ever been. False God? Hah, we have the only true God.”

“I read the leaflets, all that ‘guiding hand steering the hugest of boats with the slightest of touches’ nonsense. It was lies – I cannot explain what has happened to me any other way. You promised me a life of permanent serendipity, forever bumping into forgotten friends and meeting fascinating strangers. Everything I turned my hand to should have succeeded. What is happening? I must ask the serengent.” Antony was near tears.

“We cannot let you ask that question yourself – it cannot work if you learn anything about its plans and what it is doing for you – it creates feedback in the logic. However, I can see that you are in a very unusual position”. His attitude became fatherly, “you should go and rest, I will get some of our deifiers to examine your case. We can’t second guess a serengent, but there are a few things that we can do to investigate. Come back tomorrow, perhaps we will be able to help you then.”, he put his arm round Antonys shoulders and started to walk him towards the door, while at the same time making a series of hand signals to Steve to start the investigation he’d just promised.

Steve hurried up the spiral staircase to the top of the tower, leaving the vague sound of Antonys half hearted protestations behind him. There were only two deifiers on duty in the enormous supernet visualisation room. He bowed deeply as he entered the sacred space. Around him light danced and flowed, the global optimisation problem of happiness was being computed by millions of serengents with complicated priorities, all squabbling for computation rights, as he entered, a warning light flashed, and any visualisation involving his serengent was blanked out.

“What are you doing here?” asked one of the deifiers, “you are one of the blessed, we can’t work properly with you here.”

Steve explained his mission, and then went and sat outside on the cold wooden bench. When the abbot checked on him later that night, he was still there, waiting.

The next morning the abbot found Steve and a deifier sitting quietly in conference outside the visualisation room.

“So”, he said, what did you find?”.

Steve stammered, “The serengent prioritises important long term gains over short term, doesn’t it?”

“Yes”

“Even really long term?

“Certainly, if it’s sure enough of them and they’re important. Why?”

“We believe that Antonys serengent has been making changes to improve his character.”

“Improve his character?” The abbot was incredulous, “but it’s programmed to increase his overall happiness, not make him a better person.”

Steve shifted uncomfortably.

“We’re uncertain exactly what it is doing, but our best guess is that it has found a proof of the existence of an afterlife.”

My Great Female Age

Most of the time I wander around blissfully unaware of my age, but at this time of year, I tend to get reminded of it. I’m occasionally frustrated when I realise how old I seem to have got without writing a great epic, curing any disease, routing a dragon, rescuing a damsel, or visiting the moon (let alone punching a shark).

One friend was recently reminding me of matters chronological when, to deflect the weight of implied responsibility to do great things, I decided to point out how much older than me she was. Typically she had a response: since women live longer, in male years (like dog years?) she is younger than me.

Obviously at this point, calculations had to be done to determine if she was right. The fruits of my labour are below. Again, typically, she was right.

The life expectancy values are from 2002 for the UK.

code on jsbin

 

Technical Consultancy

I recently had the misfortune to experience Dan Browns Digital Fortress. I tend to read low quality books when I’m traveling, for example I recently took in Clancys The Teeth of The Tiger. I don’t recommend either of them.

One of the things that is particularly jarring (apart from Clancy repeating whole paragraphs word for word), is that both authors seem to think of the low quality thriller genre as modern didactic literature. In fact it is quite common that thriller writers take something that the public knows little about, do some cursory research in that field, and then try to educate the public about it. This is not a bad thing particularly, a lot of the physics I learnt came from science fiction books and has stood me in good stead over the years, but for some reason, science fiction writers take their responsibility to include lots of good science in with the fiction much more seriously than thriller writers.

Digital Fortress was particularly terrible for that. The book was roughly a quarter composed of technical information about codes and cryptography, of which I don’t think a single statement made sense. When parts of it contradicted itself, Mr Brown somehow managed to get both parts wrong. Even the central premise of the book was shocking in it’s disregard for basic common sense, let alone domain knowledge.

So, here and now, I want to offer my services to any writer who needs some help to understand concepts in computing or cryptography. I’ll read over transcripts before they are published and I’m prepared to take the necessary time and effort (for some authors a very large amount of time and effort I expect) to explain the concepts.

I’m not sure if I have the right credentials, but since I’m about three times as intelligent as a room full of the “best geniuses in the world” that are frequently gathered together in such books, who even with their “140 IQ”s can’t quite grasp the simplest things, or for some reason take three chapters to see what normal people would see immediately, I should be plenty bright enough.

I’m not particularly an expert on cryptography, about average for a computer professional I would think, but the more expert people I know would have a breakdown trying to work out how anyone could have such a poor understanding of the concepts.

Dan Brown, I’m putting 12 points on your artistic license and sentencing you to 30000 words community service. I will be your parole officer. From now on, do not write stories set since the 1960s without talking to me first.

Imponderables, partially pondered.

Derek Abbott has a hobby of collecting Imponderables. Interesting or unanswered questions. Many of them require specialized knowledge, or more rigor than I’m prepared to put into them at the moment to attack them properly, but here are a few of my thoughts on some of them.

Information theory: Imagine you are an alien from a totally different world – so different that even the building blocks of life are completely different on your planet. Now say that you land on planet Earth. You find three huge sheets of paper (i) one containing English text (ii) one listing a DNA sequence and (iii) one listing a computer program. You have no idea which is which, but you recognize you are looking at ordered bits of information – three very strange and different languages. The question is, using statistical principles and principles from information theory can you (the alien) detect any fundamental differences between the three sheets of paper so that you can distinguish between a human language, a machine language and a biological coding language? Or is it in fact impossible to distinguish them in principle?

Are we talking C or Haskell? Information theory could tell you the level of structure and redundancy in each. My guess would be that entropy could be measured and would go DNA > English > Computer program. No real idea though.

Convention: Why do clocks go clockwise?

I’ve read that this is because clocks were invented in the northern hemisphere and the hands were intended to bear a similarity to the motion of the sun. Pointing south, they go from east to west.

Ethics and Law: Imagine you have been sentenced to jail for 50 years for murder. But you are really innocent (someone set you up). You serve your sentence and when the 50 years is up, you are so angry that you kill the person who set you up. The question is: should you go to jail for a further 50 years or have you already served your sentence in the last 50 years?

On the one hand society owes you 50 years and if it realizes (you find some way of proving your innocence once freed) it should pay you back that time as best it can, on the other hand, I don’t believe that it is appropriate to be able to serve sentences in advance, otherwise anyone who had suffered oversentencing can hold the rest of society to ransom for the rest of his life. Someone could check themselves into prison for beating their wife, and when they got out, threaten the wife with beatings for the rest of her life. Allowing people to receive sentences for crimes they have not yet done, ignores the fact that the threat of committing a crime at some point in the future can also be a terrible curtailment on societies freedoms. In economics, companies can offset debts that may or may not be called in, society would have to do the same with crimes. The purpose of the 50 years sentence, justified or not was to teach not to murder. If someone comes out and immediately murders, then it was unsuccessful, and another sentence is appropriate.

Philosophy: What is truth?
Philip K Dick: Reality is that which, when you stop believing in it, doesn’t go away.
Truth is an expression of reality. People express reality by speaking or acting, nature expresses its reality by being sensed. Since we are incapable of fully expressing reality, any truth that we encounter will necessarily be partial. There is also the danger that any expression will reduce the ability of the mind that receives it to comprehend truth beyond the boundaries of that expression, or around it’s edges. I believe that’s why many mystics find it safer to define the things that are not true rather than run the risk of actually describing truth.

Law and Sociology: It could be argued that when we lock someone in jail for a crime, we cut them off from society and inevitably interfere with any possibility of normal social development of that person, and therefore perpetuate their condition. If the person is a danger to society, is there an alternative?
Although the argument might be accurate, the premise is wrong. Their normal social development so far (they were previously not cut off from society), led them to crime. Since their normal social development was harmful to society (and probably to them), it is sensible to argue that the kind of development most beneficial to them (and society) in future would be different to their “normal”. It’s the exact opposite of perpetuating their condition that is the intention. Is there an alternative to removing someone who is a danger to society from society? Yes, society can simply accept the cost of the crime and absorb it. I think this is a good idea in only a few situations (cycle of vengeance type problems). This doesn’t mean that jail is the best way of changing what is normal for their social development though. Perhaps a loving family environment may be better, assuming that that is not the environment that led to their current social development.

Philosophy: If there were no evil in the world, would good cease to have meaning?
Good would not cease to exist, but if there were nothing to distinguish it from, the word itself would lose meaning.

Law: Many paradoxes in law arise because law is black & white and real life is a continuum of grey. Law takes continuous variables and sets a threshold or boundary. Either side of the boundary is 1 or 0, ie. right or wrong. Is this for convenience because we have no better way or is there a deeper reason? If it is a matter of convenience, can we someday use technology to evaluate all the main variables and produce continuum based laws? Could we trust machines? Would it be fairer than binary laws?
Law is not binary. We already have continuum laws. Every law is required to be applied by a person to situations. Whether or not to apply any punishment in a given situation is at the discretion of a person, and how much punishment is also at the discretion of the judge. Since there are innumerable kinds of situations, situations can arise that were not forseen when the law was created, only a machine capable of understanding the intent of the law and the new, unforseen situation should be trusted (reduces to the Strong AI problem). A fundamental principle of fair laws is that those they apply to should be easily able to understand them.

Game theory: If a country has the capability to fire a nuclear missile at New York city, then conventional game theory seems to tell us that New York should point a nuclear missile at the other country. This creates a stalemate, so that no actions are taken and we are all safe. However, straight game theory needs to be expanded to include error analysis. The question is what if a nuclear missile was fired at New York and was said to be by mistake? What is the best strategy for New York now? From a game theory point of view, should New York still strike back? Also there are two possibilities to consider: the declared mistake could have been genuine or a bluff. Also another related question is that if the missile is intercepted whilst in the air, will the resulting explosion create more deaths and than if the bomb was allowed to hit the ground?
Perhaps the residents of New York should estimate the likelihood that their enemy will trigger the bomb by mistake, and ensure that their bomb has an equal margin of error. This gives the aggressor an encouragement to decrease the error for their bomb (because New York assures them that it will match any demonstrable improvement).

Extra: Irresistible force meets immovable object
Forces cannot be resisted by objects, only by other forces. So an irresistible force is simply any force not balanced by another force. The only immovable objects that can exist are frames of reference, or objects defined to be at the center of a frame of reference – a perceptor. An unbalanced force meeting an immovable object happens every time I drive a car, and what happens is that from the forces point of view, the immovable object moves (it must, unbalanced forces are defined to accelerate), and from the immovable objects point of view (my frame of reference), the rest of the universe moves.

links for 2006-12-16

Modding like it’s 1600

One of the most remarkable media players in the world is the xbox media center, homebrew software for the xbox. Sadly it requires a mod chip to run it, as microsoft have code in their console to ensure that only programs vetted by them can run (although see this article for a detailed, but interesting read about the mistakes Microsoft made).

So, what do you do when your friend comes round for a mod chipping party only to discover that your trusty old soldering iron has given up the flux?

Tealights. We should really have made them ourselves from animal fat to be properly hardcore. At least that was my claim, until I was emphatically informed that nothing done with tealights can be considered hardcore.

xboxtealightXBox modding old skool

links for 2006-12-13