473,695 Members | 2,088 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inheritance request for comment

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.

Thanks.

//----------------------------------------------------------
//rspoons
//'extend' must have two arguments, the object to inherit and
//an Array of arguments to supply the superclass.
//If the superclass requires no arguments, [null] must be passed.
Object.prototyp e.extend=functi on(){
if(arguments[1]){ //make sure argument(s) are supplied
for(var i=0;i<arguments[1].length;i++){
if(typeof(argum ents[1][i])=="string")
arguments[1][i]="'"+argumen ts[1][i]+"'"
}
if(arguments[1].length>0){Argu ments=arguments[1].join(",")}
else{Arguments= arguments[1][0]}
for(var i in eval("new arguments[0]("+Arguments+") ")){
if(i!='extend') {
g=eval("new "+arguments[0]+"("+argumen ts[1]+")."+i)
if(typeof(g)==" undefined"){
eval("this.prot otype."+i+"=new
arguments[0]("+arguments[1]+")."+i)
}
else{
eval("this.prot otype."+i+"=g")
}
}
}
}
}
//an oval class
function Oval(xaxis,yaxi s){
this.xaxis=xaxi s
this.yaxis=yaxi s
this.classid="o val"
}

//a color class
function Color(color){
this.color=colo r
}
Color.prototype .RED="#ff0000"
Color.prototype .GREEN="#00ff00 "
Color.prototype .BLUE="#0000ff"

//point class - a base class
function Point(x,y){
this.x=x
this.y=y
}

//SUBCLASSES INHERIT APPENDED CLASS METHODS AND PROPERTIES.
Point.prototype .moveto=functio n(x,y){this.x=x ;this.y=y}
Point.prototype .moveby=functio n(dx,dy){this.x +=dx;this.y+=dy }

//circle class - a subclassing class
//OBJECTS CAN INHERIT FROM MULTIPLE CLASSES.
function Circle(radius,c olor){
Circle.extend(O val,[radius,radius]) //inherits from the more
generic oval class
Circle.extend(C olor,[color]) //also inherits from the color class
this.classid="c ircle"
}

//No arguments
function CompanyTag(){
this.company="s omeco"
this.author="Ro bret Spoons"
this.date="01.1 0.04"
}

//mycircleclass subclasses a suclassing class
//FULL OOP CLASS INHERITANCE
function MyCircleclass(r adius,color,x,y ){
MyCircleclass.e xtend(Circle,[radius,color]) //Inherits from Circle
MyCircleclass.e xtend(Point,[x,y]) //Inherits from Point
MyCircleclass.e xtend(CompanyTa g,[null]) //Inherits from
CompanyTag - no arguments
this.classid="m ycircleclass"
}

//Simple utility method to itterate through and
//return an objects enumerable methods and properties
function showprops(obj){
var s=""
for(var i in obj)
if(i!='extend') s+=i+": "+eval("obj."+i )+"\n"
return s
}

//CONSTRUCTING THE SUBCLASSED OBJECT AND USING AN INHERITED METHOD
mycircle=new MyCircleclass(1 3,"blue",100,12 0)
mycircle.moveby (2,-4)
mycircle.color= mycircle.RED
alert("mycircle \n"+showprops(m ycircle)) //shows all enumerable methods
and properties

Thanks
Jul 20 '05 #1
5 1664
rd******@poncac ity.net (Robert Spoons) writes:
Can you look over this code, preferably try it, and comment?
First of all, your code is broken -- in particular some long comment
lines are broken onto the next line :) Please make sure your newsclient
doesn't break lines or post only lines so short that they are not broken.
Javascript code will not survive being wrapped as well as text, and
everybody who wants to try your code must first find and fix the errors
your newsclient has introduced (on a good day, they try, on a bad day,
they move on without commenting at all).
I believe the 'extend' function below will allow you to use full
'class inheritance' in javascript, but I would like to verify it.
Define "full class inheritance". First, define what "class" means in
a Javascript context, where there are no classes.
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.
If I read it correctly, it copies the properties of the prototype
of the class and calls(applies) the constructor.

First, code comments:
//If the superclass requires no arguments, [null] must be passed.
Why not the empty array? (or nothing, you should be able to check that)
Object.prototyp e.extend=functi on(){
Why not
Function.protot ype.extend=func tion(class,args ) {
?
Instead of writing arguments[0] and arguments[1] everywhere?
if(arguments[1]){ //make sure argument(s) are supplied for(var i=0;i<arguments[1].length;i++){
if(typeof(argum ents[1][i])=="string")
arguments[1][i]="'"+argumen ts[1][i]+"'" What if the arguement is the Javascript string "a hen's feather"? Or
"String literals use a \\ to write newlines\nYou just write \\n."?
You should also escape quotes, backslashes, special characters (ASCII<32), etc. }
if(arguments[1].length>0){Argu ments=arguments[1].join(",")}
else{Arguments= arguments[1][0]}
All this is only necessary if you use eval. Don't use eval. Never use
eval.
for(var i in eval("new arguments[0]("+Arguments+") ")){
Use this instead (no eval):
function classCloner () { return class.apply(thi s,args); };
classCloner.pro totype = class.prototype ;
var newInstance = new classCloner();
for (var i in newInstance) {
if(i!='extend') {
g=eval("new "+arguments[0]+"("+argumen ts[1]+")."+i)
Fails if the object has property names like "foo bar" or "2".
Use:

g = newInstance[i];

Then you don't need to create a new object for each property.
if(typeof(g)==" undefined"){
eval("this.prot otype."+i+"=new
arguments[0]("+arguments[1]+")."+i)
if g is undefined, you create a new object *the same way* and take
the same property again.

this.prototype[i]=newInstance[i];
}
else{
eval("this.prot otype."+i+"=g")
this.prototype[i] = g;
}
}
}
}
}

Ok, my version:

function newApply(class, argsArray) {
function createApply() {
return class.apply(thi s,argsArray);
}
createApply.pro totype = class.prototype ;
return new createApply();
}

Function.protot ype.extend = function extend(class,ar gsArray) {
var instance = newApply(class, argsArray);
for (var i in instance) {
if (i != "extend") {
this.prototype[i]=instance[i];
}
}
}

Notice that you don't extend the object with a *class*, but with an
*instance* of the class. Already there, it breaks with how it works in
class based object oriented languages.

.... //circle class - a subclassing class
//OBJECTS CAN INHERIT FROM MULTIPLE CLASSES.
function Circle(radius,c olor){
Circle.extend(O val,[radius,radius]) //inherits from the more
generic oval class
Circle.extend(C olor,[color]) //also inherits from the color class
this.classid="c ircle"
}
You change the properties of the prototype inside the constructor.
That means that if you create two objects with this constructor,
the second one overwrites the properties of the first ones prototype.
Since they extend with different objects, the result is wrong.

Example

var c1 = new Circle(2,"#ff00 00");
var c2 = new Circle(4,"#0000 00");
alert(c1.color) ; // gives #000000

Either add the new properties directly to the object being created:
I.e., here:
this.extend(Ova l,[radius,radius]);
and in extend:
this[i] = instance[i];
(that is, make objects "inherit" properties from other objects)
or only extend the class once:
Circle10.extend (Oval,[10,10]);

The problem is that you want to make classes inherit from instances.
That really doesn't make much sense, conceptually.

And: if(i!='extend') s+=i+": "+eval("obj."+i )+"\n"

don't use eval:
if(i!='extend') s+=i+": "+obj[i];

<URL:http://jibbering.com/faq/#FAQ4_39>

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #2
Lasse Reichstein Nielsen <lr*@hotpop.com > wrote in message news:<1x******* ***@hotpop.com> ...
rd******@poncac ity.net (Robert Spoons) writes:
Can you look over this code, preferably try it, and comment?


First of all, your code is broken -- in particular some long comment
lines are broken onto the next line :) Please make sure your newsclient
doesn't break lines or post only lines so short that they are not broken.
Javascript code will not survive being wrapped as well as text, and
everybody who wants to try your code must first find and fix the errors
your newsclient has introduced (on a good day, they try, on a bad day,
they move on without commenting at all).
I believe the 'extend' function below will allow you to use full
'class inheritance' in javascript, but I would like to verify it.


Define "full class inheritance". First, define what "class" means in
a Javascript context, where there are no classes.
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.


If I read it correctly, it copies the properties of the prototype
of the class and calls(applies) the constructor.

First, code comments:
//If the superclass requires no arguments, [null] must be passed.


Why not the empty array? (or nothing, you should be able to check that)
Object.prototyp e.extend=functi on(){


Why not
Function.protot ype.extend=func tion(class,args ) {
?
Instead of writing arguments[0] and arguments[1] everywhere?
if(arguments[1]){ //make sure argument(s) are supplied

for(var i=0;i<arguments[1].length;i++){
if(typeof(argum ents[1][i])=="string")
arguments[1][i]="'"+argumen ts[1][i]+"'"

What if the arguement is the Javascript string "a hen's feather"? Or
"String literals use a \\ to write newlines\nYou just write \\n."?
You should also escape quotes, backslashes, special characters (ASCII<32), etc.
}
if(arguments[1].length>0){Argu ments=arguments[1].join(",")}
else{Arguments= arguments[1][0]}


All this is only necessary if you use eval. Don't use eval. Never use
eval.
for(var i in eval("new arguments[0]("+Arguments+") ")){


Use this instead (no eval):
function classCloner () { return class.apply(thi s,args); };
classCloner.pro totype = class.prototype ;
var newInstance = new classCloner();
for (var i in newInstance) {
if(i!='extend') {
g=eval("new "+arguments[0]+"("+argumen ts[1]+")."+i)


Fails if the object has property names like "foo bar" or "2".
Use:

g = newInstance[i];

Then you don't need to create a new object for each property.
if(typeof(g)==" undefined"){
eval("this.prot otype."+i+"=new
arguments[0]("+arguments[1]+")."+i)


if g is undefined, you create a new object *the same way* and take
the same property again.

this.prototype[i]=newInstance[i];
}
else{
eval("this.prot otype."+i+"=g")


this.prototype[i] = g;
}
}
}
}
}

Ok, my version:

function newApply(class, argsArray) {
function createApply() {
return class.apply(thi s,argsArray);
}
createApply.pro totype = class.prototype ;
return new createApply();
}

Function.protot ype.extend = function extend(class,ar gsArray) {
var instance = newApply(class, argsArray);
for (var i in instance) {
if (i != "extend") {
this.prototype[i]=instance[i];
}
}
}

Notice that you don't extend the object with a *class*, but with an
*instance* of the class. Already there, it breaks with how it works in
class based object oriented languages.

...
//circle class - a subclassing class
//OBJECTS CAN INHERIT FROM MULTIPLE CLASSES.
function Circle(radius,c olor){
Circle.extend(O val,[radius,radius]) //inherits from the more
generic oval class
Circle.extend(C olor,[color]) //also inherits from the color class
this.classid="c ircle"
}


You change the properties of the prototype inside the constructor.
That means that if you create two objects with this constructor,
the second one overwrites the properties of the first ones prototype.
Since they extend with different objects, the result is wrong.

Example

var c1 = new Circle(2,"#ff00 00");
var c2 = new Circle(4,"#0000 00");
alert(c1.color) ; // gives #000000

Either add the new properties directly to the object being created:
I.e., here:
this.extend(Ova l,[radius,radius]);
and in extend:
this[i] = instance[i];
(that is, make objects "inherit" properties from other objects)
or only extend the class once:
Circle10.extend (Oval,[10,10]);

The problem is that you want to make classes inherit from instances.
That really doesn't make much sense, conceptually.

And:
if(i!='extend') s+=i+": "+eval("obj."+i )+"\n"

don't use eval:
if(i!='extend') s+=i+": "+obj[i];

<URL:http://jibbering.com/faq/#FAQ4_39>

/L


/*
Lasse Reichstein Nielsen, Thanks for your commentary - it did help.
I will be more specific in the wording I choose.
I still use eval in the function.

Thanks, I've updated the extend function - it addresses all relavent
points you made concerning the origional, and it now acts the way I
desire the function to act.
Also, the new version is much cleaner.
The function will add all publically enumarable properties and methods
of the specified target object to the calling object (effective
inheritance). I have attempted to include example use.
*/

/*
--------------------------
Much cleaner Inheritence function
Use :must be inside of object's constructor
this.extend(new ObjA(args))
(The object Inherits all enumerable properties and methods of ObjA)
*/
// obj is the object instance to inherit from
// i is an Enumerable Property or Method
// insta is a Property or Method Instance
Object.prototyp e.extend=functi on(obj){
for(var i in obj){
insta=eval("obj ."+i)
eval("this."+i+ "=insta")
}
}
/*
--------------------------
*/
function point(x,y){
this.x=x
this.y=y
}
function location(x,y){
this.extend(new point(x,y))
}
location.protot ype.moveTo=func tion(x,y){this. x=x;this.y=y}

function oval(xrad,yrad) {
this.radiusX=xr ad
this.radiusY=yr ad
}
oval.prototype. meth=function() {alert("ok")}

function circle(rad,colo r){
this.extend(new oval(rad,rad))
this.color=colo r
}
circle.prototyp e.area=function (){return
2*Math.PI*Math. pow(this.radius X,2)}

function myCircle(rad,co lor,x,y){
this.extend(new circle(rad,colo r))
this.extend(new location(x,y))
}

Object.prototyp e.showProps=fun ction(){
var s=""
for(var i in this)
if(!(i=='extend '||i=='showProp s'))s+=i +": "+eval("this."+ i)+"\n"
return s
}
a=new myCircle(3,"the hen's blue feather \n",5,10)
b=new myCircle(10,"re d",100,120)
c=new oval(4,5)
alert("a\n"+a.s howProps()+"\nb \n"+b.showProps ()+"\nc\n"+c.sh owProps())
alert("a area = "+a.area() +"\nb area = "+b.area())
Jul 20 '05 #3
rd******@poncac ity.net (Robert Spoons) writes:

Please trim the quotes :)
Use :must be inside of object's constructor
this.extend(new ObjA(args))
Why? You can always call
someObject.exte nd(someOtherObj ect)
// insta is a Property or Method Instance
You don't declare insta as a local variable.

I still use eval in the function. insta=eval("obj ."+i)
eval("this."+i+ "=insta")


Why not just
this[i] = obj[i];
It is equivalent when the property name is a valid identifier,
and, unlike your version, it works when it is not.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #4
What advantage is there to using

Object.prototyp e.extend=functi on(obj){
for(var i in obj){
insta=eval("obj ."+i)
eval("this."+i+ "=insta")
}
}

instead of

Object.prototyp e.extend = function(obj){
for (var i in obj){
this[i] = obj[i];
}
};
Jul 20 '05 #5
> Object.prototyp e.extend = function(obj){
for (var i in obj){
this[i] = obj[i];
}
};

This is it. Thanks.
Jul 20 '05 #6

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

Similar topics

10
7228
by: jeffc | last post by:
When compiling the following program, I get an error on the line specified: The base class "B" cannot be initialized because it does not have a default constructor. If I remove the "virtual" inheritance of B (so that it uses plain inheritance), it compiles fine. It also compiles if I invoke the constructor for B explicitly, as shown in the comment after the error. I'm not aware of any reason that virtual inheritance should be special...
14
12912
by: Steve Jorgensen | last post by:
Recently, I tried and did a poor job explaining an idea I've had for handling a particular case of implementation inheritance that would be easy and obvious in a fully OOP language, but is not at all obvious in VBA which lacks inheritance. I'm trying the explanation again now. I often find cases where a limited form of inheritance would eliminate duplication my code that seems impossible to eliminate otherwise. I'm getting very...
6
3803
by: Ammar | last post by:
Dear All, I'm facing a small problem. I have a portal web site, that contains articles, for each article, the end user can send a comment about the article. The problem is: I the comment length is more that 1249 bytes, then the progress bar of the browser will move too slow and then displaying that the page not found!!!! If the message is less than or equal to 1249 then no problem.
3
1726
by: Chris Kennedy | last post by:
What's the difference between importing a namespaces and inheriting.
3
1797
by: Eugene | last post by:
I'm trying to write a class which uses BinaryWriter as its base but allows for queuing of write requests Public Class QueuedBinaryWriter Inherits BinaryWriter I override all the Write methods like so: Public Overloads Overrides Sub Write(ByVal Value As Byte) m_Queue.Enqueue(New WriteRequest(MyBase.BaseStream.Position, Value)) End Sub 'same for all other Write variants
10
2874
by: Tris.Phillips | last post by:
Hi All, This may be a silly question, but: Is it possible for a child class to inherit a base classes <summary> tag info for an overridden method? Cheers, T
60
4908
by: Shawnk | last post by:
Some Sr. colleges and I have had an on going discussion relative to when and if C# will ever support 'true' multiple inheritance. Relevant to this, I wanted to query the C# community (the 'target' programming community herein) to get some community input and verify (or not) the following two statements. Few programmers (3 to7%) UNDERSTAND 'Strategic Functional Migration
3
1582
by: Jam | last post by:
Hello All, Your comment is needed on following subject,i define the Class and Inheritance as following,what do you think? Class: Class is a set of objects which shares common states and behaviors,Class can contain subclasses. Inheritance: if two classes are having two common states and behaviors or if a class is derived from another class it is called Inheritance, All's comment is needed,is this defination ok or something more should
14
4517
by: karthikbalaguru | last post by:
Hi, What could be the maximum Accepted Layers/Levels of inheritance in a normal C++ program that has private(data),protected(data) and public(data,member functions) ? On what does this depend upon ? Thx in advans, Karthik Balaguru
0
8631
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
8572
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9115
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8984
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...
1
8847
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
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
7661
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...
1
6491
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
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...

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.