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

Date实例调用hasOwnProperty('getTime')返回false的原因咨询

Why getTime isn't an own property of a Date instance but exists in the prototype chain?

Great question! Let's unpack what's happening here with your code:

const test = new Date();
test.hasOwnProperty('getTime') // false;
'getTime' in test // true

First, let's clarify the key difference between the two checks you're using:

  • hasOwnProperty() only looks at properties directly attached to the object itself—it completely ignores anything stored in the prototype chain.
  • The in operator checks if a property exists anywhere in the object's entire prototype chain, not just on the object itself.

Where is getTime actually located?

The getTime method is defined on Date.prototype—the shared prototype object that all Date instances inherit from. Your test instance doesn't have getTime as its own property (which is why hasOwnProperty returns false), but since test inherits from Date.prototype, the in operator finds the method in the prototype chain and returns true.

You can confirm this directly by checking the prototype object itself:

Date.prototype.hasOwnProperty('getTime') // true

Why is it defined this way?

This is a core efficiency choice in JavaScript. By attaching methods like getTime to the prototype instead of each individual instance, all Date objects share the same copy of the method. This saves significant memory, especially when creating many instances of built-in objects (or your own custom classes).

Your observation that "getTime isn't in the test instance's own properties but exists in the prototype chain" is exactly right—it's a standard behavior of JavaScript's prototype-based inheritance, and it's directly tied to how getTime (and nearly all built-in object methods) are defined.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:15:21