3

I am fairly new to js and I have a problem that seems I can solve by modifying the constructor of the base class. This patch here is not applied

// original class in lib
class BasePrinter {
  constructor() {
    console.log("BasePrinter constructor");
  }
}

// patching
function patchBasePrinter() {
  const originalConstructor = BasePrinter.prototype.constructor;

  BasePrinter.prototype.constructor = function(...args) {
    console.log("Patched constructor logic before");

    originalConstructor.apply(this, args);

    console.log("Patched constructor logic after");
  };
}

// Apply the patch
patchBasePrinter();

const printer = new BasePrinter(); 
// Output: BasePrinter constructor

// Expected Output:
// Patched constructor logic before
// BasePrinter constructor
// Patched constructor logic after

The other posts ive seen on this are either inconclusive or end with a solution of patching a method instead.

The real use case is to apply new logic when any class property is changed. The system is already reactive. I just want to add new logic and all the techniques I can find have to do with patching the constructor class

4
  • 1
    "This does not work" - why not? What happens instead? What's the expected behaviour? Commented Jul 31, 2024 at 8:50
  • I have edited the code for clarity. Basically the patch is not applied Commented Jul 31, 2024 at 9:08
  • does the patched constructor need to run before the original constructor? If not, I may have a solution based on this similar question Commented Jul 31, 2024 at 9:33
  • @JaromandaX no it dosen't. Commented Jul 31, 2024 at 9:46

1 Answer 1

2

Based on this similar question, with a little extra work, this could do what you need.

For example:

class BasePrinter {
    constructor() {
        console.log("BasePrinter constructor");
    }
}
class X extends BasePrinter {
    constructor(...args) {
        console.log("Before original constructor - usual limitations apply for extended class");
        super(...args);
        console.log("Your logic here");
    }
}

X.prototype = BasePrinter.prototype;
X.prototype.constructor = X;
BasePrinter = X;
new BasePrinter

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.