Class Patcher2

maginai.patcher2 submodule class

Don't instanciate directly, use from maginai.patcher2.

You can patch a method of class with patchMethod method

Constructors

Methods

Constructors

Methods

  • Patches the specified method methodName of the class cls with newMethod

    The args for newMethod is (self, originalMethod, args).

    class HelloClass {
    a = 1;
    hello(){
    console.log("Hello", this.a);
    return this.a;
    }
    }
    const helloobj = new HelloClass();

    maginai.patcher2.patchMethod(
    HelloClass, // Patches the `hello` method of the `HelloClass`...
    "hello",
    // The new `hello` method...
    (self, originalMethod, args) => {
    // Calls the original `hello` and then returns the returned value + 2 and says "Bye"
    const rtn = originalMethod(...args) + 2;
    console.log("Bye");
    return rtn;
    // The original `hello` definition currently has no args, but we passed args for compatibility.
    // For the same reason, it's recommended to return the original value (or you changed) even if the original method currently has no return value.
    });

    // After the patching, even already instanciated objects use the new method
    console.log(helloobj.hello())
    // Hello 1
    // Bye
    // 3

    Type Parameters

    • T

    Parameters

    • cls: (new () => T)

      The class which has the method methodName

        • new (): T
        • Returns T

    • methodName: string

      The name of method to be patched

    • newMethod: ((self, originalMethod, args) => void)

      self is the instance (this) on which the method is called.
      originalMethod is the original method methodName, bound to this.
      args is the list of the args passed to the method.

        • (self, originalMethod, args): void
        • Parameters

          • self: T
          • originalMethod: Function
          • args: any[]

          Returns void

    Returns void