...

View Full Version : Inheritance and function overriding question



donfuego
01-16-2012, 08:33 AM
Hi!

This is probably a classic inheritance thing...

I have two objects, C1 and C2. Both contains a callback method named 'callback'. Now, if I let C2 inherit from C1, then C1's 'callback' gets overridden by C2's. The problem is I still want C1's methods to access their own 'callback' method.

Is this possible, and is it "valid"? Am I headed down disaster lane here? Should I re-think and refactor?


Example:


function C1 () {};

C1.prototype.callback = function () {
console.log('c1 called');
};

C1.prototype.call = function () {
//do stuff
this.callback();
};

function C2 () {};

C2.prototype = new C1();

C2.prototype.callback = function () {
console.log('c2 called');
};


var obj = new C2();
obj.call();


Output:


c2 called

Regards

Don

felgall
01-16-2012, 08:48 AM
The usual way to do this is to set up way to reference the C1 prototype from within C2

eg.

C2.uber = C1.prototype;

You would then be able to use C2.uber in place of C2 whenever you want to access methods of C1 that were overwritten by methods in C2.

obj.uber.call();

donfuego
01-16-2012, 08:57 AM
Ah, of course!

Since I'd like my parent classes to be "autonomous", I tried changing the C1 call method like this:



C1.prototype.call = function () {
//do stuff
C1.prototype.callback();
};

It seems to work the way I want, but is it good practice?

In reality the callback is being called back by external API. The good thing (it seems) using this approach, is that I don't need to wrap the callback in a function
extAPIcall ( function () { C1.prototype.callback(response); } ) since the prototype is (kind of) static. I suppose, in a way, this could be some what compared with doing a Class::function() call in other languages.

felgall
01-16-2012, 09:43 AM
The main thing to remember is that JavaScript is a prototyping language and not an object oriented language - so attempting to use OO techniques the same way you would in an OO language results in far less efficient and messier code than if you make proper use of JavaScript's prototyping features.

All objects exist as objects in JavaScript - each is effectively the singleton static example of its own class (as classes do not exist in JavaScript). So there is nothing wrong with C1.prototype.callback where you know that it is the C1 version you want to run.

donfuego
01-16-2012, 10:22 AM
Thanks for clarifying. I'm still trying to get my head around it though. I have my roots in old school procedural programming, and OO is still a bit alien to me. JS, in some ways, reminds me of the procedural past, but with an OO approach...or something. Anyhow, it makes my head spin! :)

Dormilich
01-17-2012, 07:45 AM
as of late (5th edition) you can also access the prototype chain directly with Object.getPrototypeOf(obj) instead of obj.prototype



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum