首页 > 解决方案 > 在javascript中动态获取所有类函数

问题描述

如何获取我的所有类的函数及其继承的类的函数的数组

例如

class Foo extends Bar {
      funcA() {}
}

class Bar {
      funcB() {}
}

const instanceFoo = new Foo();

getClassFunctions(instanceFoo); // should return an array ['funcA', 'funcB'];

我做了一个返回类的函数名的函数,但它只适用于类自己的属性

const getAllFuncs = (obj) => {
    const proto = Object.getPrototypeOf (obj);
    const names = Object.getOwnPropertyNames (proto);
    return names.filter (name => typeof obj[name] === 'function' && name !== 'constructor');
}

标签: javascript

解决方案


简单地循环,去每个原型,当你到达时可能会停止Object.prototype。我也会从对象本身开始,而不是它的原型,因为可以在构造过程中添加方法:

const getAllFuncs = (obj) => {
    // Remember which names we've checked
    const checked = new Set();
    // The function names we'll return
    const funcs = [];
    while (obj && obj !== Object.prototype) {
        for (const name of Object.getOwnPropertyNames(obj)) {
            if (name !== "constructor" && !checked.has(name)) {
                // Remember we've checked this name
                checked.add(name);
                const value = obj[name];
                if (typeof value === "function") {
                    // Remember this function
                    funcs.push(name);
                }
            }
        }
        // Go up a level
        obj = Object.getPrototypeOf(obj);
    }
    return funcs;
};

原因checkedfuncs一个对象可能有一个以foo非函数命名的属性不同,但它的原型也可能有一个foo带有函数的属性。这很少见,但可行:

class Base {
    foo() {
    }
}
class Sub extends Base {
    constructor() {
        super();
        this.foo = 42;
    }
}
const sub = new Sub();
const names = getAllFuncs(sub);

names不包括foo因为sub.foois 42,而不是函数。


推荐阅读