asimes
asimes

Reputation: 5916

JavaScript Polymorphism variable inheritance

I'm practicing polymorphism in JavaScript (first time trying) based on different examples I've found online. I know that in other languages I can access the variables of the super class from the extended one and am wondering how to do this correctly in JavaScript. The code below doesn't throw any error (at least as far as Firefox's Error Console is concerned), but statement is undefined in ExtendedClass.

function MyClass() {
  this.statement = "I'm a class with a method";
  this.speak = function() {
    alert(this.statement);
  }
}
var mInstance = new MyClass();
mInstance.speak();

function ExtendedClass() {
  Object.create(MyClass);
  this.speak = function() {
    alert(this.statement+" and I extend a class");
  }
}
var eInstance = new ExtendedClass();
eInstance.speak();

Can I access statement from ExtendedClass? Is this a good method of implementing polymorphism?

Upvotes: 3

Views: 801

Answers (3)

maiorano84
maiorano84

Reputation: 11971

Prototypes are what you're looking for.

var MyClass = function(){}; //Empty Constructor
MyClass.prototype = {
    statement: "I'm a class with a method",
    speak: function(){
        alert(this.statement);
    }
};
var ExtendedClass = function(){}; //Empty Constructor
ExtendedClass.prototype = new MyClass();
ExtendedClass.prototype.speak = function(){
    alert(this.statement+" and I extend a class");
};
var eInstance = new ExtendedClass();
eInstance.speak();

Upvotes: 1

Ben McCormick
Ben McCormick

Reputation: 25728

You can use MyClass.call(this) to set the local variables, and then use Object.create to set the prototype, like this

function MyClass() {
  this.statement = "I'm a class with a method";
  this.speak = function() {
    alert(this.statement);
  }
}
var mInstance = new MyClass();
mInstance.speak();

function ExtendedClass() {
  MyClass.call(this);
  this.speak = function() {
    alert(this.statement+" and I extend a class");
  }
}
ExtendedClass.prototype = Object.create(MyClass.prototype);
var eInstance = new ExtendedClass();
eInstance.speak();

You can see more at the MDN Docs

Upvotes: 2

RyanFishman
RyanFishman

Reputation: 695

I do it like this

function MyClass() {
  this.statement = "I'm a class with a method";
  this.speak = function() {
    alert(this.statement);
  }
}
var mInstance = new MyClass();
mInstance.speak();

function ExtendedClass() {
  MyClass.call(this);
  this.speak = function() {
    alert(this.statement+" and I extend a class");
  }
}
var eInstance = new ExtendedClass();
eInstance.speak();

Not sure if this is the best syntax but I know this works and you properly inherit MyClass with all it's public methods and variables.

Upvotes: 1

Related Questions