With a new project comes a new tweak to the inheritance model I use with Javascript. To be honest this is turning into a modding situation. It always feels like we can inherit better with Javascript, that we can produce fitter objects. Here's the structure.

function BaseObj(constructor) {
//Base attributes go here
BaseObj.prototype = { //Base methods go here};

function Character(constructor) {
BaseObj.call(this, constructor);
//Character Attributes go here
Character.prototype = Object.create(BaseObj.prototype);
Character.prototype.constructor = Character;
//Character methods below
Character.prototype.TestMethod = function(){}

You can see the basic structure fairly clearly. I have a base object which can have attributes and methods.

Things are slightly more complex for my child object. First off it calls the parent whenever it itself is called. We also modify the prototype, first to change it into the parent's prototype but then we restore its own constructor so it has an identity distinct from its parent. Again attributes and methods can be added, though slightly differently to the parent.

The upsides of all this are we get Character objects with their own firm identity. They pass an instanceof Character check. However they are also very much the children of their parent, they pass an instanceof BaseObj check. Each instance of Character is also distinct. if I create test1 as Character and test2 as a Character, then change a value on test1, test2 will be unaffected. That sounds simple but remember javascript is very much a pass-by-reference language so if I later say test2 = test1, test2 will now be a reference to the object that is test1 instead of its own object.

The downsides are it looks messy. My previous version of inheritance scooped up all of this and contained it within the object's function method at the cost of some weirdness. Now we have perfect inheritance but in order to add methods to my Character class I have to write them outside its own definition.

The quest for the holy grail continues.

No comments

Add Comment

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
Standard emoticons like :-) and ;-) are converted to images.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications.
BBCode format allowed