Tuesday, May 8, 2012

Extending/overriding in JavaScript?

I want to write a small game using JavaScript and <canvas> but first I want to nail the "correct" or at least common approach to working with Objects.



One topic I am having trouble understanding in particular is how I could implement overriding of method.



When I create an Object, I may have this:



function MyObject()
{
var base = {};

base.i = 0;
base.update = function()
{
base.i ++;
}

return base;
}


Then when I create another Object that should start with the same members, I use this:



function AnotherObject()
{
var base = new MyObject();

base.j = 0;

return base;
}


I want to add more content to AnotherObject.update() while still running the logic I have in MyObject.update(), but when I do this within AnotherObject():



base.update = function()
{
j ++;
}


Then I of course lose the logic I added in MyObject.update().



How can I write AnotherObject.update() so that it also calls the original update() method defined by MyObject?





No comments:

Post a Comment