I want to use some very simple inheritance in Javascript without any libraries (jQuery, Prototype, etc.) and I'm forgetting how to do this.
I know how to create a simple non-inherited object:
function Foo(x)
{
this.x = x;
}
Foo.prototype = {
inc: function() { return this.x++; }
}
which I can then use as follows:
js>f1=new Foo(0)
[object Object]
js>f1.inc()
0
js>f1.inc()
1
js>f1.inc()
2
But how would I add a subclass with one additional method that inherits the Foo "inc" method, without changing the Foo class?
function Bar(x)
{
this.x = x;
}
Bar.prototype = new Foo();
Bar.prototype.pow = function(y) { return this.x+"^"+y+"="+Math.pow(this.x,y); }
That seems right except for this weirdness with the constructor; I have to call the Foo constructor once to create the Bar prototype, and when Bar's constructor is called, it seems like there's no way to call the Foo constructor.
Any suggestions?
initfunction. Of course, you could useapplyon the previous constructor (using the newBarobject as the context) as well to to mimicbase()(C#) orsuper()(Java).function Bar(x) { this.constructor.prototype.constructor.apply(this,[x]); }