Thomas 'PointedEars' Lahn <Po*********@nurfuerspam.de> writes:
The proper way is
Bar.prototype = new Foo;
The proper way to what?
<http://devedge.netscape.com/library/manuals/2000/javascript/1.5/guide/obj2.html#1008388>
I think this is a bad way of trying (and failing) to emulate class
based inheritance in a non-class based language. Instead of inheriting
from the generic class, you inherit from a single instance (which is
what prototype based inheritance is all about). You lack the call to
the superclass' constructor, and all your instances share the properties
of the prototype.
Example where it fails:
---
function Stack() {
this.stack = [];
}
Stack.prototype.push = function(x){this.stack.push(x);}
Stack.prototype.pop = function(){return this.stack.pop;}
function CountableStack() {}
CountableStack.prototype = new Stack();
CountableStack.prototype.count = function() {return this.stack.length;}
---
This looks plausible, if one reads the Netscape link above. It
fails terribly, since all CountableStack's use the same internal
stack.
---
var s1 = new CountableStack();
var s2 = new CountableStack();
s1.push(42);
s2.push(37);
alert(s1.count());
---
So, IMO, it's *not* a propert way to do anything.
A closer to proper way to make class-like inheritance in Javascript is
(for Bar(x,y,z) extending Foo(x,y)):
---
function Bar(x,y,z) {
Foo.call(this,x,y);
this.z=z;
}
Bar.prototype = clone(Foo.prototype);
---
where clone is
---
function clone(obj) {
function Cloner(){};
Cloner.prototype = obj;
return new Cloner();
}
---
(or *maybe* just use an instance of Foo as prototype, if you know
that it doesn't matter that it has been initialized once).
/L
--
Lasse Reichstein Nielsen -
lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'