且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

每次使用JS调用类中的任何函数时都要运行一个函数

更新时间:2023-11-24 11:24:10

您可以通过遍历所有自己的属性名称( Object.keys for..in 在这里不起作用,因为类方法不可枚举),然后用调用原始方法又调用中间件的新方法替换原始方法.通过这种方式,类的行为不会改变,但是会调用中间件.

You could rewrite all the methods of the classes prototype by iterating over all own property names (Object.keys or for..in would not work here as class methods are not enumerable) and then replacing the original methods by a new method that calls the original method but also calls the middleware. Through that the classes behaviour doesnt change, but the middleware gets called.

 class MyClass {
    a() { console.log("a"); }
 }

 function middleware() { 
    console.log("works");
 }

 for(const key of Object.getOwnPropertyNames(MyClass.prototype)) {
     const old = MyClass.prototype[key];
     MyClass.prototype[key] = function(...args) {
       middleware(...args);
       old.call(this, ...args);
     };
 }

 (new MyClass).a();