Kristian Stacey
Kristian Stacey

Reputation: 13

calling inherited methods javascript prototypes

I have an extended "class" extending a base "class" using prototypes. The problem I'm having is how do I call methods defined on the prototype of the base class (base methods) from the inheriting classes prototype method.

function Obj() {
    this.name;
}

Obj.prototype.baseMethod = function(usefulstuff) {
    alert(usefulstuff);
}

function extendedObj() {
    Obj.call(this);
}

extendedObj.prototype = new Obj();

extendedObj.prototype.constructor = extendedObj;

extendedObj.prototype.anotherMethod = function() {
    this.baseMethod(stuff);//gives this.baseMethod is not a function and direct call gives baseMethod is not defined
}

var a = new extendedObj();

a.anotherMethod();

Surely because the prototypes of both objects are the same and methods have only been added and because the prototype methods are public, this should be fine, unless this isn't how prototype chaining works?

Upvotes: 1

Views: 37

Answers (1)

Transcendence
Transcendence

Reputation: 2706

You can affix a _super property referring to the super class. See here for more details. http://ejohn.org/blog/simple-javascript-inheritance/

Another approach is to directly call the method from the super class's prototype using Superclass.prototype.desiredMethod.call(this, args...). See here for more details. http://blog.salsify.com/engineering/super-methods-in-javascript

Upvotes: 1

Related Questions