【问题标题】:Get all methods of any object?获取任何对象的所有方法?
【发布时间】:2017-03-07 20:49:16
【问题描述】:

在python word中有dir()函数

返回该对象的有效属性列表

我找到的 JS 单词:

Object.getOwnPropertyNames

Object.keys

但它们并不显示所有属性:

> Object.getOwnPropertyNames([])
[ 'length' ]

如何获取所有属性和方法的列表

concat, entries, every, find.... 

以 Array() 为例?

【问题讨论】:

标签: javascript


【解决方案1】:

您可以使用Object.getOwnPropertyNamesObject.getPrototypeOf 来遍历原型链并收集每个对象的所有自己的属性。

var result = []
var obj = []
do {
  result.push(...Object.getOwnPropertyNames(obj))
} while ((obj = Object.getPrototypeOf(obj)))

document.querySelector("pre").textContent = result.join("\n")
<pre></pre>

这会处理所有属性,无论它们是继承的还是可枚举的。但是,这不包括 Symbol 属性。要包含这些,您可以使用Object.getOwnPropertySymbols

var result = []
var obj = []
do {
  result.push(...Object.getOwnPropertyNames(obj), ...Object.getOwnPropertySymbols(obj))
} while ((obj = Object.getPrototypeOf(obj)))

【讨论】:

  • 既然 OP 需要方法,就应该有一个 Function 对象(或至少是可调用对象)的过滤器。
  • @RobG:也许吧。 OP 提到了“属性和方法”,所以我不确定应该包含多少。
【解决方案2】:

Object.getOwnPropertyNames(Array.prototype)

尝试以您发布的方式获取值不起作用的原因是因为您正在请求Array 对象的单个实例 的属性名称。由于多种原因,每个实例将仅具有该实例唯一的属性值。由于在Array.prototype 中找到的值不是特定实例所独有的——这是有道理的,并非所有数组都会为length 共享相同的值——它们对于Array 的所有实例都是共享/继承的。

【讨论】:

    【解决方案3】:

    你可以使用Object.getOwnPropertyNames

    Object.getOwnPropertyNames() 方法返回一个直接在给定对象上找到的所有属性(可枚举或不可枚举)的数组。

    console.log(Object.getOwnPropertyNames(Array.prototype));
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      【解决方案4】:

      此方法将允许您从对象的特定实例中提取所有键和功能(忽略不需要的):

      const ROOT_PROTOTYPE = Object.getPrototypeOf({});
      
      function getAllKeys(object) {
          // do not add the keys of the root prototype object
          if (object === ROOT_PROTOTYPE) {
              return [];
          }
      
          const names = Object.getOwnPropertyNames(object);
      
          // remove the default constructor for each prototype
          if (names[0] === 'constructor') {
              names.shift();
          }
      
          // iterate through all the prototypes of this object, until it gets to the root object.
          return names.concat(getAllKeys(Object.getPrototypeOf(object)));
      }
      
      

      【讨论】:

        猜你喜欢
        • 2015-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-16
        • 1970-01-01
        • 2016-12-28
        • 1970-01-01
        相关资源
        最近更新 更多