列出Javascript中的所有类方法



解释我的问题的最好方法是通过下面的代码:

class SomeClass {
SomeMethod() {
console.log("SomeMethod was called");
}
}
var someInstance = new SomeClass();
// The below expression expected to return True but is returns False
console.log(
someInstance.hasOwnProperty("SomeMethod")
);
// The below expression is expected to include SomeMethod in the return list, but it doesn't
console.log(
Object.keys(someInstance)
);
// The below expression is expected to include SomeMethod in the return list, but it doesn't
console.log(
Object.getOwnPropertyNames(someInstance)
);
// The below expression works fine which confrms that the function exists.
someInstance.SomeMethod();

CodeSandbox联系

我希望Object.keys()Object.getOwnPropertyNames()返回所有属性,包括在构造此对象的类的类定义中定义的方法,但由于某种原因两者都没有。

如果这两个函数都不能在这种情况下工作,那么我怎么能列出一个类实例的所有方法?

您可以创建自定义函数来实现这个

class SomeClass {
SomeMethod() {
console.log("SomeMethod was called");
}
}
var someInstance = new SomeClass();
function getMethods(obj) {
return Object.getOwnPropertyNames(Object.getPrototypeOf(obj))
.filter(m => 'function' === typeof obj[m])
}
console.log(getMethods(someInstance))

最新更新