"Enhance" existing JS class in ECMAScript 2017 (Firefox v55)?

80 views Asked by At

Basically I'm wondering whether it is possible to redefine a method at class level, not instance level, as sought here.

Just to make clear, also, I want to be able to call the original method (on this) from within the enhanced/replacement method.

I tried implementing the chosen answer, "decorating the constructor", but it doesn't appear to work in FF55's "SpiderMonkey" version of ES2017: I get a message saying the class "requires new".

Doing a bit of googling I found this article. This man talks about a whole bunch of concepts which I wasn't even aware existed in Javascript! My knowledge of JS hasn't gone much beyond the Javascript Definitive Guide 6th Edition, although I do use Promises and async/await a lot (I'm hoping a new edition of the JS Def Guide will come out one day...).

So are there any experts out there who know of a way to, essentially, "enhance" (i.e. re-engineer, not extend) existing JS classes in ES2017?

2

There are 2 answers

1
mike rodent On BEST ANSWER

Whoops... thanks to Dovydas for this. I was obviously having a mental block!

const superObserve = MutationObserver.prototype.observe;
MutationObserver.prototype.observe = function( target, config ){
    console.log( 'blip');
    superObserve.call( this, target, config );
}
3
mokahaiku On

Let say you have a class named Original, which has a render method, which you want to update.

class Original {
  render() {
    return 'Original';
  }
}

You can update it by changing the render method of the prototype of the Original function like so:

Original.prototype.render = function() {
  return 'Changed';
}

If you want to add a new method to your class this is how you do it:

Original.prototype.print = function() {
  return 'Printing...';
}

Then you can use these methods as usual.

const changed = new Original().render();
const printed = new Original().print();