Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


2 Answers

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

like image 149
Ben McCormick Avatar answered Aug 17 '26 23:08

Ben McCormick


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.

like image 37
RyanFishman Avatar answered Aug 17 '26 23:08

RyanFishman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!