每次使用JS调用类中的任何函数时都要运行一个函数 [英] Run a function every time any function in class is called using JS

查看:33
本文介绍了每次使用JS调用类中的任何函数时都要运行一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的简单班级:

I have simple class like this:

module.exports = class MyClass {

    function middleware() {
        console.log('call me before')
    }

    function a() {

    }
    function b() {

    }

    function c() {

    }
}

所以想法是,当有人调用函数a,b,c时,我想在执行a,b,c之前调用中间件.我该怎么办?

So Idea is, when someone call function a, b, c I want call middleware before execute a, b, c. How can I do it?

因此,我可以将Middleware()放到每个函数中,但是我想要一些动态的方法来做到这一点.

So, I can put middleware() to each function, but I want some dynamic way how to do this.

推荐答案

您可以通过遍历所有自己的属性名称( 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();

这篇关于每次使用JS调用类中的任何函数时都要运行一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆