动态获取javascript中的所有类函数

时间:2019-06-13 08:58:28

标签: 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');
}

1 个答案:

答案 0 :(得分:1)

简单循环,转到每个原型,可能在到达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.foo42,不是函数。