We can use the Object.getOwnPropertyNames()
function to get all the property names linked to an object.
我们可以使用Object.getOwnPropertyNames()
函数来获取链接到对象的所有属性名称。
Then we can filter the resulting array, to only include that property name if it’s a function.
然后,我们可以过滤结果数组,以仅在该属性名称为函数的情况下包括该名称。
We determine if it’s a function by using typeof
on it.
我们通过使用typeof
来确定它是否是一个函数。
For example here is how we might create a utility function to do what we need:
例如,这是我们可能如何创建实用程序函数来执行所需的操作:
getMethods = (obj) => Object.getOwnPropertyNames(obj).filter(item => typeof obj[item] === 'function')
This lists only the methods defined on that specific object, not any method defined in its prototype chain.
这仅列出在该特定对象上定义的方法,而不列出其原型链中定义的任何方法。
To do that we must take a slightly different route. We must first iterate the prototype chain and we list all the properties in an array. Then we check if each single property is a function.
为此,我们必须采取稍微不同的路线。 我们必须首先迭代原型链,然后在数组中列出所有属性。 然后,我们检查每个属性是否都是一个函数。
An easy way to make sure we don’t duplicate methods as we navigate the prototype chain (like constructor
which is always present), we use a Set data structure that makes sure values are unique:
一种确保在导航原型链时不重复方法的简单方法(例如始终存在的constructor
),我们使用Set数据结构来确保值是唯一的:
const getMethods = (obj) => {
let properties = new Set()
let currentObj = obj
do {
Object.getOwnPropertyNames(currentObj).map(item => properties.add(item))
} while ((currentObj = Object.getPrototypeOf(currentObj)))
return [...properties.keys()].filter(item => typeof obj[item] === 'function')
}
Example usage:
用法示例:
getMethods("")
getMethods(new String('test'))
getMethods({})
getMethods(Date.prototype)
翻译自: https://flaviocopes.com/how-to-list-object-methods-javascript/