I'd like to add a method to a method:
class MyClass {
public foo(text: string): string {
return text + ' FOO!'
}
// Some magical code which adds the method `bar` to `foo`.
}
const obj = new MyClass();
console.log(obj.foo('thing'));
console.log(obj.foo.bar('other thing'));
Is this possible? I've found a similar case for functions:
function Sum(x: number) { /*...*/ }
namespace Sum {
export function empty() { /*...*/ }
}
Is there a way to do the same with methods of a class?
I'd like have the code in the class, not monkeypatched after the object has been created.
You can access the function on the classes prototype and do whatever you like with it. I don't think it's especially pretty, but you can do something like this:
class MyClass {
constructor(myName) {
this.myName = myName
this.constructor.prototype.foo.bar = (function(a) {
console.log(this.myName, "calling foo.bar with:", a)
}).bind(this)
}
foo(text) {
return text + ' FOO!'
}
}
const obj = new MyClass("Mark");
obj.foo.bar('thing')
console.log(obj.foo('test'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With