FMCorz
8/24/2016 - 6:40 AM

Extending (or overriding) class methods in Javascript

Extending (or overriding) class methods in Javascript

class MyParentClass {
  myMethod() {
    this.i++;
    return this.i;
  }
}

class MyChildClass extends MyParentClass {
  myMethod() {
    var returnValue = super();
    return returnValue + 1;
  }
}
// This is a parent class.
var MyParentClass = function() {};
MyParentClass.prototype.myMethod = function() {
    this.i++;
    return this.i;
};

// Make new class.
var MyChildClass = function() {
    // Call the parent constructor.
    MyParentClass.prototype.constructor.apply(this, arguments);
};

// This is the line that makes the class extend the other one.
MyChildClass.prototype = Object.create(MyParentClass.prototype);

// Sets the constructor back to what it should be.
MyChildClass.prototype.constructor = MyChildClass;

// We override the myMethod with our own.
MyChildClass.prototype.myMethod = function() {
    // If we want to extend rather, we call this:
    var returnValue = MyParentClass.prototype.myMethod.apply(this, arguments);
    return returnValue + 1;
};