faqts : Computers : Programming : Languages : JavaScript : Language Core : prototypes/inheritance

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

23 of 26 people (88%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

Is it possible to call a method in a super class?

Jan 9th, 2003 09:09
Daniel LaLiberte, Martin Honnen,


Although the 'super' keyword is reserved in JavaScript,
there is no super object or comparable feature in JavaScript.  
But at least for a two level 
inheritance hierarchy the methods of the "superclass" constructor are 
acessible as
  this.constructor.prototype.methodName
Although this expression gives you the function, the problem is
that we cannot call as a method by using a normal function call.
JavaScript1.3 introduced apply and call for that so with NN4+ 
you can write:
  this.constructor.prototype.methodName.call(this);
   // or if you have an array of arguments:
  this.constructor.prototype.methodName.apply(this, arguments);
IE4/5 with JScript5 does not support apply and call (but IE5.5 does) 
so you have to assign the function as a property of the object, 
and then it can be used as a method:
  this.super_methodName =
    this.constructor.prototype.methodName;
  this.super_methodName();
If that all sounds too abstract consider the following example which 
defines a "class" God and a "subclass" NetGod and calls 
the "superclass"' toString method in the subclass.
function God (name) {
  this.name = name;
}
God.prototype.toString = function () {
  return 'Name of God: ' + this.name + '\n';
}
var allah = new God ('Allah');
alert(allah.toString());
function NetGod (name, url) {
  this.constructor(name);
  this.url = url;
}
NetGod.prototype = new God();
/* NN4
NetGod.prototype.toString = function () {
  var super_toString = this.constructor.prototype.toString;
  return super_toString.call(this) + 'Home of God: ' + this.url + '\n';
}
*/
NetGod.prototype.toString = function () {
  this.super_toString = this.constructor.prototype.toString;
  return this.super_toString(this) + 'Home of God: ' + this.url + '\n';
}
var kibo = new NetGod ('Kibo', 'http://www.kibo.com');
alert(kibo.toString())