0

I have a library in old style like this

function A() { }
A.prototype.hello = function (s) {
    console.log(s);
}
module.exports = A;

Some application is using it like this

const {inherits} = require('util');
const A = require('./lib.js')
function B() {
    A.call(this);
}
inherits(B,A);
const b = new B();
b.hello('test');

I want to use a new style in library without any changes in application

class A {
    hello(s) {
        console.log(s);
    }
}
module.exports = A.constructor // ???????

Question: What do I need to add in the last line for correct work?

Guillaume Georges
  • 3,878
  • 3
  • 14
  • 32
Yaroslav Gaponov
  • 1,997
  • 13
  • 12
  • You've already asked this question before, the answer is still the same: it's not possible to use `A.call(this)` when `A` is a `class`, so don't use classes if you cannot change the subclassing code. – Bergi May 26 '21 at 14:40
  • If you insist, your best bet would be `function A() { const instance = Reflect.construct(RealA, arguments, this.constructor); Object.assign(this, instance); Object.setPrototypeOf(this, Object.getPrototypeOf(instance)); } A.prototype = RealA.prototype` where `RealA` is your `class` and the `A` function acts as a weird intermediate that copies the properties of the real instance to the object created by `new B`. – Bergi May 26 '21 at 14:43

0 Answers0