我想知道如何列出一个对象可用的所有方法,例如:

 alert(show_all_methods(Math));

这应该打印:

abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min, pow, random,round, sin, sqrt, tan, …

当前回答

var methods = [];
for (var m in obj) {
    if (typeof obj[m] == "function") {
        methods.push(m);
    }
}
alert(methods.join(","));

这样,你将得到所有你可以在obj上调用的方法。这包括它从原型中“继承”的方法(如java中的getMethods())。如果你只想看到那些由obj直接定义的方法,你可以用hasOwnProperty检查:

var methods = [];
for (var m in obj) {        
    if (typeof obj[m] == "function" && obj.hasOwnProperty(m)) {
        methods.push(m);
    }
}
alert(methods.join(","));

其他回答

var methods = [];
for (var m in obj) {
    if (typeof obj[m] == "function") {
        methods.push(m);
    }
}
alert(methods.join(","));

这样,你将得到所有你可以在obj上调用的方法。这包括它从原型中“继承”的方法(如java中的getMethods())。如果你只想看到那些由obj直接定义的方法,你可以用hasOwnProperty检查:

var methods = [];
for (var m in obj) {        
    if (typeof obj[m] == "function" && obj.hasOwnProperty(m)) {
        methods.push(m);
    }
}
alert(methods.join(","));

简单的回答是,你不能,因为数学和日期(在我的脑海中,我相信还有其他的)不是正常的对象。为了看到这一点,创建一个简单的测试脚本:

<html>
  <body>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        alert("Math: " + Math);
        alert("Math: " + Math.sqrt);
        alert("Date: " + Date);
        alert("Array: " + Array);
        alert("jQuery: " + jQuery);
        alert("Document: " + document);
        alert("Document: " + document.ready);
      });
    </script>
  </body>
</html>

你可以看到它作为一个对象的表现方式和文档的表现方式是一样的,但是当你真正尝试在那个对象中观察时,你会看到它是原生代码而不是以相同的方式为枚举公开的东西。

我相信有一个简单的历史原因,为什么你不能列举 使用内置对象的方法,例如Array。原因如下:

方法是prototype-object的属性,比如Object.prototype。 这意味着所有object实例都将继承这些方法。这是 为什么你可以在任何对象上使用这些方法。例如,使用. tostring()。

所以IF方法是可枚举的,我将遍历{a:123} 使用:"for(输入{a:123}){…会发生什么?多少次 循环会被执行吗?

在我们的例子中,对于单个键“a”,它将被迭代一次。但也 Object.prototype的每个可枚举属性一次。因此,如果 方法是可枚举的(默认情况下),那么在任何对象上的任何循环都将循环 对所有继承的方法也是如此。

与ES6类和继承很好地工作的方法

这可能是大多数像我这样的ES6新手在寻找“如何列出对象方法”时的意思。

本文已改编自:https://stackoverflow.com/a/47714550/895245

// Define getMethods.
const isGetter = (x, name) => (Object.getOwnPropertyDescriptor(x, name) || {}).get
const isFunction = (x, name) => typeof x[name] === "function";
const deepFunctions = x =>
  x && x !== Object.prototype &&
  Object.getOwnPropertyNames(x)
    .filter(name => isGetter(x, name) || isFunction(x, name))
    .concat(deepFunctions(Object.getPrototypeOf(x)) || []);
const distinctDeepFunctions = x => Array.from(new Set(deepFunctions(x)));
const getMethods = (obj) => distinctDeepFunctions(obj).filter(
    name => name !== "constructor" && !~name.indexOf("__"));

// Example usage.

class BaseClass {
  override() { }
  baseMethod() { }
}

class DerivedClass extends BaseClass {
  override() { }
  get myGetter() { }
  static myStatic() { }
}

const obj = new DerivedClass();
const methods = getMethods(obj)
methods.sort()
const assert = require('assert')
assert(methods[0] === 'baseMethod')
assert(methods[1] === 'myGetter')
assert(methods[2] === 'override')

console.log(getMethods(Math))

注意它还包括基类的方法,因为大多数用户都想知道他们可以在对象上调用哪些方法。

它似乎也与Math一起工作,它输出:

[
  'abs',    'acos',  'acosh',  'asin',
  'asinh',  'atan',  'atanh',  'atan2',
  'ceil',   'cbrt',  'expm1',  'clz32',
  'cos',    'cosh',  'exp',    'floor',
  'fround', 'hypot', 'imul',   'log',
  'log1p',  'log2',  'log10',  'max',
  'min',    'pow',   'random', 'round',
  'sign',   'sin',   'sinh',   'sqrt',
  'tan',    'tanh',  'trunc'
]

在Node.js 14.17.0上测试。

受到其他答案的启发,这里有一种查找所有方法的递归方法:

// Find all methods of an object, up to the root prototype
function findAllMethods(obj, methods = []) {
  if (!obj) {
    return [...new Set(methods)];
  }
  
  const props = Object.getOwnPropertyNames(obj);
  return findAllMethods(Object.getPrototypeOf(obj), [
    ...methods,
    ...props.filter(prop => typeof obj[prop] === 'function'),
  ]);
}