Skip to content

Instantly share code, notes, and snippets.

@FMCorz
Last active August 24, 2016 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FMCorz/08731374ba13b371c8cfa7f000fd72d3 to your computer and use it in GitHub Desktop.
Save FMCorz/08731374ba13b371c8cfa7f000fd72d3 to your computer and use it in GitHub Desktop.
Extending (or overriding) class methods in Javascript
// 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;
};
class MyParentClass {
myMethod() {
this.i++;
return this.i;
}
}
class MyChildClass extends MyParentClass {
myMethod() {
var returnValue = super();
return returnValue + 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment