More JavaScript Fun
By Adrian Sutton
Quite some time ago I talked about redefining and rewriting handler functions in JavaScript, but what if you want to add or redefine methods in an existing class? JavaScript classes1 are based on prototyping so the model is somewhat different to actual object oriented languages. Here’s one way to define a class, MyThing:
function MyThing { this.doStuff = doStuff; } function doStuff() { }
Note the use of function assignment in there, just like for handler functions. This is one way to do classes in JavaScript, and it’s not really the best – once you get your head around prototypes you’ll probably find that using them directly is much clearer. There’s plenty of tutorials around the web on JavaScript prototyping so I’ll leave explaining it to the experts.
Back to the task at hand, you might be tempted2 to modify the class by redefining the constructor:
MyThing = eval("function MyThing { this.doStuff = otherStuff; }");
This doesn’t work. Instead, simply modify the prototype for the class:
MyThing.prototype.doStuff = otherStuff;
This becomes far more intuitive when you think more directly in terms of prototypes. A clearer way of defining the original MyThing prototype would be:
function MyThing() { } MyThing.prototype { doStuff: doStuff; // Alternatively functions could be declared inline: moreStuff: function() { ... } }
So now we can add or change functions in a class that has been defined elsewhere. What possible things could we do with that? There’s cheesecake tomorrow for any of my work mates that can guess what I’m planning to use this for3.
1 – I'm not quite sure they are strictly speaking classes, but the linguistic differences are unimportant.↩
2 – as admittedly I was, and did in fact try↩
3 – the presence of cheesecake may be more related to it being my birthday tomorrow than to someone working out what I'm up to.↩