JavaScript中获取各类数据类型的可用方法与属性:为何Object.getOwnPropertyNames无法获取实例方法?
为什么
Object.getOwnPropertyNames()拿不到数字实例的toFixed方法? 这个问题戳中了JavaScript原型链机制的一个关键点——自身属性和继承属性的区别,我来给你理清楚:
首先得明确Object.getOwnPropertyNames()的核心作用:它只会返回目标对象自身直接定义的属性(包括可枚举和不可枚举的),完全不会涉及原型链上继承来的属性。
那回到你的例子:
let n = 1234.567; console.log(n.toFixed(1)); // 正常输出 1234.6 console.log(Object.getOwnPropertyNames(n)); // 输出空数组 []
你能调用n.toFixed(),但getOwnPropertyNames找不到它,原因很简单:toFixed根本不是n这个实例自身的属性,而是定义在Number.prototype(Number构造函数的原型对象)上的。
JavaScript的基本类型(数字、字符串、布尔值)在调用方法时,会自动触发临时包装对象的机制:当你访问n.toFixed时,JS会把原始数字1234.567临时包装成一个Number类型的对象,然后沿着原型链向上查找——先找这个临时对象自身的属性,找不到就去Number.prototype上找,刚好toFixed就在这里,所以能正常执行。
你可以做两个验证来确认:
- 查看
Number.prototype的自身属性,就能看到toFixed:console.log(Object.getOwnPropertyNames(Number.prototype)); // 会包含 "toFixed"、"toString" 等方法 - 检查
n是否真的拥有toFixed这个自身属性:console.log(n.hasOwnProperty('toFixed')); // 输出 false
如果想要获取包括原型链在内的所有属性,可以用for...in循环(默认遍历可枚举的继承属性),或者手动遍历原型链并收集属性:
function getAllProperties(obj) { let props = []; let current = obj; while (current) { props = props.concat(Object.getOwnPropertyNames(current)); current = Object.getPrototypeOf(current); } return props; } console.log(getAllProperties(n)); // 会包含Number.prototype和Object.prototype上的所有属性
内容的提问来源于stack exchange,提问作者carl.hiass
相关产品推荐
相关产品推荐

