Javascript class inheritance
I always believed there was no such thing as class inheritance in Javascript. As I'm just working on a rather large Javascript application I thought I might well use a derived class an discovered that there is really a way to do it.
function a()
{
}
a.prototype.propA = 'Hello';
a.prototype.methodA = function()
{
this.thisPropA = 'World';
}
function b()
{
a.apply(this, arguments);
this.methodA();
this.thisPropB = 'works!'
}
b.prototype = new a();
b.prototype.propB = 'It';
b.prototype.method2 = function()
{
alert(this.thisPropA + ' ' + this.propA + ' ' + this.propB + ' ' + this.thisPropB)
}
o = new b();
o.method2();
To inherit from one class, you have to assign an instance of it to the protopype of the derived class. It seems not very explicit, but it works as expected. To call the parent constructor you have to use its apply() method to execute it in the this-context of the derived class.
Tags für diesen Artikel: JavaScript
About this entry
You’re currently reading “Javascript class inheritance,” an entry on Raimund Meyer's personal blog
- Geschrieben von:
- Raimund Meyer um
30.05.2009 / 14:00
Last updated 06.09.2010





Noch keine Kommentare
Jump to comment form | Kommentare RSS | Trackback für spezifische URI dieses Eintrags