Last active
August 24, 2016 07:28
-
-
Save FMCorz/08731374ba13b371c8cfa7f000fd72d3 to your computer and use it in GitHub Desktop.
Extending (or overriding) class methods in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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