Reputation: 3819
I have one class, let's say base class with constructor and one derived class, inheriting that base class as following
class base {
constructor() {
// Here I need classname, methodname and arguments. i.e. "derived, methodToBeCalled and 5"
}
}
class derived extends base {
methodToBeCalled(paramA: number) {
}
}
new derived().methodToBeCalled(5)
As shown in above code, I need class name method name and method arguments in base class (I have mentioned constructor, but fine if there is alternative common way through which I can get these details)
Is this possible using Typescript? (or lets say Javascript...!!!)
Upvotes: 0
Views: 1106
Reputation: 24221
One option is to use getOwnPropertyNames, you can call this on the derived class to work out what function are derived, and then wrap them inside another function, inside this function you can then use call to pass the args down to the derived.
Below is a simple example..
class base {
constructor() {
const baseMethods = new Set(Object.getOwnPropertyNames(base.prototype));
for (const method of Object.getOwnPropertyNames(Object.getPrototypeOf(this))) {
if (!baseMethods.has(method)) {
this[method] = (...args) => {
console.log('Before: ' + method + ' with params', args);
this.constructor.prototype[method].call(this, ...args);
console.log('After: ' + method);
}
}
}
}
thisIsNotWrapped() {
console.log('This should not be wrapped');
}
}
class derived extends base {
methodToBeCalled(paramA) {
console.log(`paramA = ${paramA}`);
}
anotherMethod(paramB) {
console.log(`paramA = ${paramB}`);
}
}
var x = new derived();
x.methodToBeCalled(123);
x.anotherMethod('Hello');
x.thisIsNotWrapped();
Upvotes: 1