如何查找JavaScript中Array、Number、String等内置对象的所有方法?已尝试Object.getOwnPropertyNames(Number)无法获取全部方法
查询JavaScript内置对象所有方法的可行方案
嘿,我明白你为啥用Object.getOwnPropertyNames(Number)拿不全方法了——这个方法只能抓取Number构造函数自身的静态方法/属性(比如Number.isNaN、Number.parseInt),但那些我们常用的实例方法(比如toFixed()、toString())其实都挂载在Number.prototype原型对象上,自然不会被这个方法获取到。
下面给你几个能拿到完整方法的解决办法:
1. 合并构造函数自身与原型的方法
写一个简单的工具函数,同时收集构造函数自身的静态方法,以及原型上的实例方法,还能过滤掉非函数的常量(比如Number.MAX_VALUE):
function getAllBuiltInMethods(constructor) { // 获取构造函数自身的所有属性(包括不可枚举的) const ownStaticProps = Object.getOwnPropertyNames(constructor); // 获取原型对象上的所有属性(包括不可枚举的) const protoInstanceProps = Object.getOwnPropertyNames(constructor.prototype); // 合并并去重,避免重复项 const allProps = [...new Set([...ownStaticProps, ...protoInstanceProps])]; // 过滤出所有方法(排除常量、属性等非函数项) return allProps.filter(prop => { return typeof constructor[prop] === 'function' || typeof constructor.prototype[prop] === 'function'; }); } // 测试Number对象 console.log(getAllBuiltInMethods(Number)); // 测试Array对象 console.log(getAllBuiltInMethods(Array));
2. 包含继承自上层原型的方法(比如Object的方法)
如果需要连继承来的方法(比如所有对象都有的toString()、valueOf())一起获取,可以遍历整个原型链:
function getAllInheritedMethods(constructor) { const methodSet = new Set(); // 遍历原型链,收集所有实例方法 let currentProto = constructor.prototype; while (currentProto !== null) { Object.getOwnPropertyNames(currentProto).forEach(prop => { if (typeof currentProto[prop] === 'function') { methodSet.add(prop); } }); currentProto = Object.getPrototypeOf(currentProto); } // 添加上构造函数自身的静态方法 Object.getOwnPropertyNames(constructor).forEach(prop => { if (typeof constructor[prop] === 'function') { methodSet.add(prop); } }); return Array.from(methodSet); } // 测试String对象,会包含来自Object的继承方法 console.log(getAllInheritedMethods(String));
3. 最直观的方式:浏览器控制台直接查看
不用写代码的话,直接在浏览器开发者工具的控制台里输入构造函数名(比如Number)或者原型对象(比如Number.prototype),展开后就能看到所有属性和方法——包括不可枚举的,控制台会清晰分类展示静态方法、实例方法和常量,非常方便。
内容的提问来源于stack exchange,提问作者Alper Feim
相关产品推荐
相关产品推荐

