473,695 Members | 1,871 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inheritance : access to the superClass' methods via prototype

Hi all,

What I am trying to achieve is an 'inherits' method similar to Douglas
Crockford's (http://www.crockford.com/javascript/inheritance.html) but
that can enable access to the superclass' priviledged methods also. Do
you know if this is possible ?

In the following example, I create an ObjectA (variable a), an ObjectB
which inherits ObjectA (variable b) and an ObjectC which inherits
ObjectA (variable c1). The 'toString ()' method of ObjectC refers to
the 'toString ()' method of ObjectA. This is possible because the
'Object.inherit s ( superClass )' method adds a reference to the
superClass of an object in the object's prototype.

If I understood things correctly, the prototype is the same for all
objects of class ObjectC. Therefore, I should be able to only add the
reference to the superClass once. That is the purpose of the
'Object.initial izedPrototypes' array : it keeps track of the objects
for which a reference to the superClass has been added to the
prototype.

However, when I create another instance of ObjectC (variable c2), its
prototype doesn't contain any reference to the superClass.

A workaround for this problem consists in adding a reference to the
superClass for each instance of the inferiting object (either by
bypassing the check to Object.initiali zedPrototypes or by adding the
reference to a priviledged member such as 'this.superClas s' instead of
'this.prototype .superClass'). However, in terms of memory usage or of
"programmin g elegance", this seams to defeat the whole purpose of using
prototypes.

Here is the code, if any of you have got ideas they are more than
welcome !

Thanks,

Stephane.

PS : I also included the 'Object.isInsta nceOf ( classOrSuperCla ss )'
method although it is not used in the examples. It's there just in case
you spot anything wrong with it. It seems to work but it might show
some flaws in my understanding of OOP in JavaScript.

<html>
<head>
<script language = "JavaScript "><!--

///////////////////////////////
///// Array
///////////////////////////////
Array.prototype .indexOf = function ( element ) {
for ( var i = 0; i < this.length; i ++ )
if ( this [ i ] == element ) return i;
return -1;
}

///////////////////////////////
///// Object
///////////////////////////////
// array of names of previously initialized objects.
// this enables the inherits method to not add the superClass for an
inheriting class twice.
Object.prototyp e.initializedPr ototypes = new Array ();

Object.prototyp e.inherits = function ( superClass ) {
this.prototype = new superClass;
this.prototype. constructor = this;
if ( Object.initiali zedPrototypes.i ndexOf ( this.constructo r.name )
== -1 ) {
// this is the first time the object calls 'inherits', I must therefore
add the superClass to the prototype.
// if I understood things correctly, this should add a "pointer" to
superClass for all instances of this object.
this.prototype. superClass = new superClass;
Object.initiali zedPrototypes.p ush ( this.constructo r.name );
}
// the line below proves me wrong ! this.prototype. superClass is
undefined (when called for variable c2)
else alert ( this.constructo r.name + ' should already have a
superClass : ' + this.prototype. superClass );
superClass.call ( this );
return this;
}

Object.prototyp e.isInstanceOf = function ( classOrSuperCla ss ) {
var ptr = this;
do {
if ( ptr.constructor == classOrSuperCla ss ) return true;
ptr = ptr.prototype.s uperClass;
} while ( ptr != null );
return false;
}

///////////////////////////////
///// Example
///////////////////////////////
function ObjectA () {
this.letter = 'A';
this.toString = function () {
return 'I am an instance of ObjectA.\nMy favorite letter is ' +
this.letter + '.\n';
};
}

function ObjectB () {
this.inherits ( ObjectA );
this.letter = 'B';
}

function ObjectC () {
this.inherits ( ObjectA );
this.letter = 'C';
// overriding toString method of ObjectA, using the equivalent of
super.toString
this.toString = function () {
return this.prototype. superClass.toSt ring.call ( this ) + 'I am an
ObjectC.\n';
};
}

var a = new ObjectA (), b = new ObjectB (), c1 = new ObjectC ();

// the following line will generate an alert (see
Object.prototyp e.inherits method)
// because an ObjectC has already been instanciated.
var c2 = new ObjectC ();

// alerts which call the toString method of each object.
alert ( a );
alert ( b );
alert ( c1 );
alert ( c2 );

//--></script>
</head>
</html>

Sep 20 '05 #1
2 3026
Hi

No Javascript doesn't have a real "super" property.

I have made a simple example of how it's implymented here
http://km0ti0n.blunted.co.uk/viewng....28223185937500 .

By the looks of things it's how you have done it.

Sep 20 '05 #2
thanks !

although your solution wasn't exactly what I had intended, it pointed
me in the right direction.

The important line in your bit of code is :
subClass.protot ype.FunctionA = function() {/*[...]*/};

Whereas my way of writing it was this :
this.prototype. FunctionA = function() {/*[...]*/};

This led me to test whether both this and subClass pointed to the same
thing, which they don't ! It is still a little mysterious to me why it
is this way, but my conclusion is that the object's prototype is the
common structure for all of its instances, but the actual instance can
change the prototype "locally" (i.e. without impacting the structure of
the other instances of the same class). Therefore, to enable your
solution in a generic function (i.e. without making an explicit
reference to a specific subClass), I changed :

this.prototype. superClass = /*[...]*/;

to :

this.constructo r.prototype.sup erClass = /*[...]*/;

Below is the corrected code (for whomever it might be useful). Thanks
km0ti0n for your help (and thanks to Douglas Crockford's site on
javascript (http://www.crockford.com/javascript/) for putting me on the
right track),

Stephane.

PS : If some of you still spot errors in this code, please post to tell
me : I'm not yet sure this version is correct ...

///////////////////////////////
///// Array
///////////////////////////////
Array.prototype .indexOf = function ( element ) {
for ( var i = 0; i < this.length; i ++ )
if ( this [ i ] == element ) return i;
return -1;
}

///////////////////////////////
///// Object
///////////////////////////////
// array of names of previously initialized objects.
// this enables the inherits method to not add the superClass for an
inheriting class twice.
Object.prototyp e.initializedPr ototypes = new Array ();

Object.prototyp e.inherits = function ( superClass ) {
this.prototype = new superClass;
this.prototype. constructor = this;
if ( Object.initiali zedPrototypes.i ndexOf ( this.constructo r.name )
== -1 ) {
// this is the first time the object calls 'inherits', I must therefore
add the superClass to the prototype.
this.constructo r.prototype.sup erClass = new superClass;
Object.initiali zedPrototypes.p ush ( this.constructo r.name );
}
superClass.call ( this );
return this;
}

Object.prototyp e.isInstanceOf = function ( classOrSuperCla ss ) {
if ( classOrSuperCla ss == Object ) return true;
var ptr = this;
do {
if ( ptr.constructor == classOrSuperCla ss ) return true;
ptr = ptr.constructor .prototype.supe rClass;
} while ( ptr != null );
return false;
}

///////////////////////////////
///// Example
///////////////////////////////
function ObjectA () {
this.letter = 'A';
this.toString = function () {
return 'I am an instance of ObjectA.\nMy favorite letter is ' +
this.letter + '.\n';
};
}

function ObjectB () {
this.inherits ( ObjectA );
this.letter = 'B';
}

function ObjectC () {
this.inherits ( ObjectA );
this.letter = 'C';
// overriding toString method of ObjectA, using the equivalent of
super.toString
this.toString = function () {
return this.constructo r.prototype.sup erClass.toStrin g.call ( this
) + 'I am an ObjectC.\n';
};
}

var a = new ObjectA (), b = new ObjectB (), c1 = new ObjectC (), c2
= new ObjectC ();

// alerts which call the toString method of each object.
alert ( a );
alert ( b );
alert ( c1 );
alert ( c2 );

Sep 20 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

37
2830
by: Mike Meng | last post by:
hi all, I'm a newbie Python programmer with a C++ brain inside. I have a lightweight framework in which I design a base class and expect user to extend. In other part of the framework, I heavily use the instance of this base class (or its children class). How can I ensure the instance IS-A base class instance, since Python is a fully dynamic typing language? I searched and found several different ways to do this:
5
1664
by: Robert Spoons | last post by:
Can you look over this code, preferably try it, and comment? I believe the 'extend' function below will allow you to use full 'class inheritance' in javascript, but I would like to verify it. The extend function allows the following: 1) inheriting from multiple classes, 2) inheriting an inherited classes inheritances (awkward to say), 3) inheriting appended prototype methods and properties of inhertited classes.
2
6339
by: Kevin Newman | last post by:
I have been playing around with a couple of ways to add inheritance to a JavaScript singleton pattern. As far as I'm aware, using an anonymous constructor to create a singleton does not allow any kind of inheritance: singletonObj = new function() { this.prop = true; } Here are two ways to create a singleton with inheritance:
36
2710
by: Pacific Fox | last post by:
Hi all, haven't posted to this group before, but got an issue I can't work out... and hoping to get some help here ;-) I've got a base object that works fine with named arguments when called on it's own. However when I call the child object I get an error " has no properties (in firefox)." I simple test:
6
1880
by: burningodzilla | last post by:
Hi all - I'm preparing to dive in to more complex application development using javascript, and among other things, I'm having a hard time wrapping my head around an issues regarding "inheritance" using the prototype property. I realize there are no classes in JS, that code therefore lives in objects instead of class definitions, and that "inheritance" must be achieved prototypically and not classically. That said, on with the code. Say I...
4
2020
by: amidzic.branko | last post by:
I'm trying to solve a problem using inheritance and polymorphism in python 2.4.2 I think it's easier to explain the problem using simple example: class shortList:
11
2246
by: John | last post by:
Hi All, Although C# has Generics, it still does not support the generic programming paradigm. Multiple inheritance is required to support real generic programming. Here is a simple design pattern to illustrate this. Problem: I need to expose two lists of objects from a high-level class. I would like to expose these lists as read-only, but require write access internally.
1
3281
by: ITMozart | last post by:
I wrote this piece of code: class A { public A() { someMeth(); } public void someMeth() { out.println(entries); }
6
14870
by: howa | last post by:
Consider example: Animal = function(age) { this.age = age; }; Animal.prototype.sleep = function() { alert("Animal Sleeping..."); };
0
8630
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8982
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8825
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7660
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4340
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4579
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3003
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2272
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1976
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.