【问题标题】:List built in JavaScript standard object methods列出内置 JavaScript 标准对象方法
【发布时间】:2013-03-29 03:41:43
【问题描述】:

有没有办法列出所有 JavaScript 标准对象方法?

我的意思是我正在尝试获取 String 的所有内置方法,所以我在想,我确实尝试过这样做:

for( var method in String ) {
    console.log( method );
}

// I also tried this:
for( var method in String.prototype ) {
    console.log( method );
}

但没有运气。此外,如果有一种解决方案适用于所有 ECMAScript 标准类/对象的方法。

编辑: 我想指出,该解决方案也应该在服务器端环境中工作,例如 rhino 或 node.js。

并且尽可能不使用第三方 API/框架。

【问题讨论】:

标签: javascript node.js rhino


【解决方案1】:

dir不会给你你需要的东西吗?

console.log(dir(method))

编辑:

这可行(请尝试John Resig's Blog 了解更多信息):

Object.getOwnPropertyNames(Object.prototype) 给出:

["constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "__defineGetter__", "__lookupGetter__", "__defineSetter__", "__lookupSetter__"]

Object.getOwnPropertyNames(Object) 给出:

["length", "name", "arguments", "caller", "prototype", "keys", "create", "defineProperty", "defineProperties", "freeze", "getPrototypeOf", "getOwnPropertyDescriptor", "getOwnPropertyNames", "is", "isExtensible", "isFrozen", "isSealed", "preventExtensions", "seal"]

【讨论】:

  • 方法 dir 返回 undefined。我在想的是一个函数或某种过程,它将返回一组内置方法。
  • Object.getOwnPropertyNames(function () {}).indexOf('bind') //> -1 node 的自动补全器在 bind 上进行查找,因此必须有一种方法来获取对象的 all 方法。除非完成者中有特定对象的临时代码,但我会发现这是一个奇怪的设计决定。
【解决方案2】:

您应该能够通过检查属性类型来获取方法列表,如here 所述

也可以试试getOwnPropertyNames

【讨论】:

  • 是的,我的例子和那里的答案相似。我只需要添加一个条件来测试它是否是一个函数,但据我观察它也不起作用。
【解决方案3】:

【讨论】:

    【解决方案4】:

    所以这里有一种方法可以挤出更多的属性:

    > function a () {}
    undefined
    > Object.getOwnPropertyNames(a)
    [ 'length',
      'name',
      'arguments',
      'caller',
      'prototype' ]
    > a.bind
    [Function: bind]
    > // Oops, I wanted that aswell
    undefined
    > Object.getOwnPropertyNames(Object.getPrototypeOf(a))
    [ 'length',
      'name',
      'arguments',
      'caller',
      'constructor',
      'bind',
      'toString',
      'call',
      'apply' ]
    

    我不是 javascript 人,但我猜发生这种情况的原因是因为 bindtoStringcallapply 可能是从更高的继承级别继承的(这在这种情况?)

    编辑:顺便说一句,这是我实现的一个,它尽可能地追溯到原型。

    function getAttrs(obj) {
        var ret = Object.getOwnPropertyNames(obj);
        while (true) {
            obj = Object.getPrototypeOf(obj);
            try {
                var arr = Object.getOwnPropertyNames(obj);
            } catch (e) {
                break;
            }
    
            for (var i=0; i<arr.length; i++) {
                if (ret.indexOf(arr[i]) == -1)
                    ret.push(arr[i]);
            }
        }
    
        return ret;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-09
      • 2019-02-03
      • 1970-01-01
      • 2014-09-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2012-01-15
      相关资源
      最近更新 更多