Simplified / best way to call shadow prototype method?

I am writing a hierarchy of objects in JavaScript, I would like to call a method for the parent of the object when I shadowed this method in the object.

eg:.

var Base = function Base(msg) { this.msg = msg; } Base.prototype.log = function(){ console.log("base log: " + this.msg); } var Sub = function Sub(msg) { Base.call(this, msg); } Sub.prototype = Object.create(Base.prototype); Sub.prototype.log = function() { console.log("sub log"); this.__proto__.__proto__.log.call(this); // This works but __proto__ Object.getPrototypeOf(Object.getPrototypeOf(this)).log.call(this); // This works but is verbose super.log(); // This doesn't work } var sub = new Sub('hi'); sub.log(); 

Look at the three lines at the bottom of the Sub.prototype.log function - is there a better way to do what I'm trying to do there?

The second line is the best I could come up with, but very verbose.

+6
source share
2 answers

super not defined, obviously this will not work.

You might want to try:

 Sub.prototype.log = function() { console.log("sub log"); Base.prototype.log.call(this); } 

Another way is to use the following method to inherit classes:

 function extend(Child, Parent) { var F = function() { }; F.prototype = Parent.prototype; Child.prototype = new F(); // better to make it static (better practice in OOP world) // eg Child.super = ..., // but in your case: Child.prototype.super = Parent.prototype; } 

So here is an example:

 // .. extend(Sub, Base); Sub.prototype.log = function() { console.log("sub log"); this.super.log.call(this); } 

In the case of ES6 :

 class Base { constructor(msg) { this.msg = msg; } log(){ console.log("base log: " + this.msg); } } class Sub extends Base { constructor(msg) { super(msg); } log() { console.log("sub log"); super.log(); } } var sub = new Sub('hi'); sub.log(); 
+2
source

If you want to save the original method without using the Base name, you can capture it using closure before changing it.

 (function() { var superLog = Sub.prototype.log; Sub.prototype.log = function() { console.log("sub log"); superLog(); }; })(); 

This way, no matter how you inherit from Base .

Side Note: The terminology you are looking for is an β€œoverride" of the underlying method.

+1
source

All Articles