Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a method to a class method in typescript (javascript)

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.

like image 761
André C. Andersen Avatar asked Jul 14 '26 11:07

André C. Andersen


1 Answers

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'))
like image 92
Mark Avatar answered Jul 16 '26 00:07

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!