Date实例调用hasOwnProperty('getTime')返回false的原因咨询
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
inoperator 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

