获取类的函数(方法)

我必须动态获取ES6类的属性和功能。这有可能吗?


使用for ... in循环,我只能循环访问类实例的属性:


class Foo {

  constructor() {

    this.bar = "hi";

  }

  someFunc() {

    console.log(this.bar);

  }

}

var foo = new Foo();

for (var idx in foo) {

  console.log(idx);

}

输出:


bar


米脂
浏览 475回答 3
3回答

慕的地10843

此功能将获取所有功能。是否继承,是否可枚举。包括所有功能。function getAllFuncs(obj) {    var props = [];    do {        props = props.concat(Object.getOwnPropertyNames(obj));    } while (obj = Object.getPrototypeOf(obj));    return props.sort().filter(function(e, i, arr) {        if (e!=arr[i+1] && typeof obj[e] == 'function') return true;    });}做测试getAllFuncs([1,3]);控制台输出:["constructor", "toString", "toLocaleString", "join", "pop", "push", "concat", "reverse", "shift", "unshift", "slice", "splice", "sort", "filter", "forEach", "some", "every", "map", "indexOf", "lastIndexOf", "reduce", "reduceRight", "entries", "keys", "constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "__defineGetter__", "__lookupGetter__", "__defineSetter__", "__lookupSetter__"]注意它不返回通过符号定义的函数。

胡子哥哥

班级的成员不可枚举。要获得它们,您必须使用Object.getOwnPropertyNames:var propertyNames = Object.getOwnPropertyNames(Object.getPrototypeOf(foo));// orvar propertyNames = Object.getOwnPropertyNames(Foo.prototype);当然,这不会继承方法。没有任何一种方法可以为您提供所有这些。您必须遍历原型链并分别获取每个原型的属性。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript