Base class function call - class inheritance in JavaScript

Please see 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(); 

This should print both "I initialize the base class" and "I initialize the child class."

I need to inherit the MyBaseClass class, but still you can call its init () method at the beginning of the new init () method.

How to do it?

+7
source share
3 answers

jQuery extend does not create inheritance, but "Merges 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(); 

Result :

 I am initializing the base class I am initializing the child class 
+17
source

jsFiddle Demo

A couple of things. extend really just adds properties; it does little. So you need to have a function for your class ready to inherit from the base class, and then use the extension for this class prototype.

 function MyChildClass(){}; MyChildClass.prototype = new MyBaseClass(); $.extend(MyChildClass.prototype, { init: function() { MyBaseClass.prototype.init(); console.log('I am initializing the child class'); } }); 

Here is another approach I would like to use for inheritance - when the specifics of the methods will be a problem - this is saving the base class in its own property

 function MyChildClass(){}; MyChildClass.prototype = new MyBaseClass(); MyChildClass.prototype.base = new MyBaseClass(); $.extend(MyChildClass.prototype, { init: function() { this.base.init(); console.log('I am initializing the child class'); } }); 
+1
source

Another prototype based template to achieve this:

 MyBaseClass = function(a) { this.a = a; }; MyBaseClass.prototype = { init: function() { console.log('I am initializing the base class'); } }; MyChildClass = function() {}; MyChildClass.prototype = $.extend(new MyBaseClass(), { init: function() { this.super.init.call(this); console.log('init child'); }, super: MyBaseClass.prototype, constructor: MyChildClass }); var a = new MyChildClass(); a.init(); 

Output:

 I am initializing the base class init child 

Here this.super stores a reference to the base class.

+1
source

All Articles