I have a class having structure like :
class A {
constructor() {}
myMethod() {
console.log('in my method');
}
}
I want to make a method that will accept className and methodName like :
modifyClassMethod(className, methodName)
This method should wrap the whole body of methodName specified into a callback during runtime.
So if I do,
modifyClassMethod(A, myMethod)
Now during runtime the body of myMethod of class A should get changed to
myMethod() {
nr.recordMe('here', {
console.log('in my method').
})
}
Now when I will create a new object of A class, then I will get modified value of myMethod.
How can I achieve this in TS or JS ?.
You can get help of Decorator Design Pattern. It's also called as wrapper. In Typescript you can do;
interface IClassInterface{
myMethod():void
}
class classA implements IClassInterface{
constructor() {}
myMethod() {
console.log('in my method');
}
}
class AWrapper implements IClassInterface{
constructor(private classA:IClassInterface){}
myMethod(somestring?:string) {
//this.classA.myMethod(); either do this, or do sth else
console.log("wrapper works", somestring);
this.classA.myMethod();
}
}
and when using;
let aClass = new classA();
let IClassWrapper = new AWrapper(aClass);
IClassWrapper.myMethod('here');