gpt4 book ai didi

javascript - 获取 Node.js 中类的可用函数列表

转载 作者:搜寻专家 更新时间:2023-10-31 23:23:57 25 4
gpt4 key购买 nike

我正在尝试寻找一种干净、简单的方法来使用命令行简单地获取 Node.js 中某个类的可用函数列表。

根据之前的网络搜索,我偶然发现了 Object.getOwnPropertyNames() 但似乎这个函数不一致,否则我不明白为什么它适用于某些类而不适用于其他类.

让我们研究一个例子,也许有人可以提供帮助。目前,node -v 为这个例子输出 v4.4.5。

首先,假设我想获取 Math 类的函数列表。从 Node 控制台,这很好用,我得到:

[root@localhost /]# node
> Object.getOwnPropertyNames(Math)
[ 'E',
'LN10',
'LN2',
'LOG2E',
'LOG10E',
'PI',
'SQRT1_2',
'SQRT2',
'random',
'abs',
'acos',
'asin',
'atan',
'ceil',
'exp',
'floor',
'log',
'round',
'sqrt',
'atan2',
'pow',
'max',
'min',
'imul',
'sign',
'trunc',
'tanh',
'asinh',
'acosh',
'atanh',
'hypot',
'fround',
'clz32',
'cbrt',
'cos',
'sin',
'tan',
'sinh',
'cosh',
'log10',
'log2',
'log1p',
'expm1' ]
>

很酷。行得通。

现在,由于 Node.js 更多是关于服务器端编程的,让我们看看同样的事情是否适用于几乎在 Node.js 的每个“hello world”类型示例中使用的通用类:http .服务器

让我们尝试同样的事情:

> Object.getOwnPropertyNames(http.Server)
[ 'length', 'name', 'prototype', 'super_' ]

嗯....将此与文档进行比较here ,它似乎缺少基本的东西,如 server.close()server.listen()。进一步查看文档,此类是 net.Server 的子类,所以也许我必须查看该类的方法。让我们看看这是否有效:

> Object.getOwnPropertyNames(net.Server)
[ 'length', 'name', 'prototype', 'super_' ]

嗯...如果我们比较 net.Server 的文档我们缺少像 server.address()server.getConnections() 等基本函数。

谁能帮我理解:

(a) 为什么 getOwnPropertyNames 似乎显示了某些类的所有方法而不显示其他类的所有方法,并且...(b) 是否有另一种“官方”方法可以简单地列出 Node.js 中对象的可用函数,而无需阅读 API 文档来获取这样的列表?

最佳答案

如果您查看 docs对于 getOwnPropertyNames,您将看到:

If you want only the enumerable properties, see Object.keys() or use a for...in loop (although note that this will return enumerable properties not found directly upon that object but also along the prototype chain for the object unless the latter is filtered with hasOwnProperty()).

这就是说 getOwnPropertyNames()Object.keys() 只会返回对象本身的可枚举属性,不会给你有关对象原型(prototype)的任何信息。

所以似乎没有内置函数来实现你想要的,所以你必须自己编写代码。例如:

for (var prop in obj) {
console.log('obj.' + prop + ' = ' + obj[prop]);
}

注意:您可以制作自己的实用程序库,包装这个想法,以便您可以将它包含在您想要运行它的任何项目中。

关于javascript - 获取 Node.js 中类的可用函数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39714679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com