如何在JavaScript中列出对象的所有方法

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/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值