Calling base class function - class inheritance in JavaScript
class, inheritance, javascript
Solution
jQuery's extend doesn't build inheritance but "Merge the contents of two or more objects together into the first object".
Use prototype based inheritance to achieve your inheritance and explicitly call the "super" method :
MyBaseClass = function(a) {
this.a = a;
};
MyBaseClass.prototype.init = function() {
console.log('I am initializing the base class');
};
MyChildClass = function(a) {
this.a = a;
}
MyChildClass.prototype = Object.create(MyBaseClass.prototype); // makes MyChildClass "inherit" of MyBaseClass
MyChildClass.prototype.init = function() {
MyBaseClass.prototype.init.call(this); // calls super init function
console.log('I am initializing the child class');
};
var child= new MyChildClass();
child.init();
Output :
I am initializing the base class
I am initializing the child class
Problem
Please check out the following example: ``` MyBaseClass = function(a) { this.a = a; }; $.extend(MyBaseClass.prototype, { init: function() { console.log('I am initializing the base class'); } }); MyChildClass = $.extend(MyBaseClass, { init: function() { MyBaseClass.prototype.init(); console.log('I am initializing the child class'); } }); var = new MyChildClass(); var.init(); ``` Тhis should output both 'I am initializing the base class' and 'I am initializing the child class'. I need to be able to inherit the class MyBaseClass, but still to be able to call his init() method at the beginning of the new init() method. How do I do that?