You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Object.getOwnPropertyNames()的两个疑问:原型方法未列出与父类属性返回

Understanding Object.getOwnPropertyNames() Behavior in JavaScript

Great questions! Let's break these down one by one to clear up the confusion around how Object.getOwnPropertyNames() works.

1. Why aren't prototype methods included in Object.getOwnPropertyNames(animal)?

First, let's recap what Object.getOwnPropertyNames() does: it returns only the properties that are directly owned by the object itself—not properties inherited from the object's prototype chain.

In your code:

function Animal(name, weight) { this.name = name; this.weight = weight; }
Animal.prototype.eat = function() { return `${this.name} is eating!`; }
Animal.prototype.sleep = function() { return `${this.name} is going to sleep!`; }
Animal.prototype.wakeUp = function() { return `${this.name} is waking up!`; }
var animal = new Animal('Kitten', '5Kg');

The eat, sleep, and wakeUp methods are defined on Animal.prototype, which is the prototype of the animal instance. These are not properties of the animal object itself—they're properties of the prototype object that animal inherits from.

To get those prototype methods, you need to call Object.getOwnPropertyNames() directly on the prototype:

console.log(Object.getOwnPropertyNames(Animal.prototype)); 
// Output: ["constructor", "eat", "sleep", "wakeUp"]

If you want to collect all properties (own + inherited enumerable ones), you'd need to traverse the prototype chain manually, but Object.getOwnPropertyNames() is intentionally limited to an object's own properties.

2. Why does Object.getOwnPropertyNames(triangle) include the parent class's type property?

This comes down to how ES6 class inheritance works with super(). When you call super("triangle") inside the Triangle constructor, it invokes the parent Shape constructor—but crucially, this inside the Shape constructor refers to the Triangle instance, not a separate Shape instance.

So when the Shape constructor runs this.type = type, it's adding the type property directly to the triangle object. That makes type an own property of triangle, not an inherited one. You can confirm this with:

console.log(triangle.hasOwnProperty('type')); // Output: true

Since type is an own property of the triangle instance, Object.getOwnPropertyNames() includes it alongside a, b, and c. If you wanted to only get properties defined in the Triangle constructor, you could manually filter the results, but this behavior is expected because super() executes the parent constructor in the context of the child instance.


内容的提问来源于stack exchange,提问作者Lisa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:19:06