Date.getTime()与Date.now()

编程入门 行业动态 更新时间:2024-10-27 13:28:22
本文介绍了Date.getTime()与Date.now()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我注意到now()只能由Date对象调用.getTime()只能由日期实例调用.

I noticed that now() can only be called by the Date object. getTime() can only be called by an instance of date.

var dd1 = new Date(); //console.log(dd1.now()); //Throws error -> TypeError: Object Mon Aug 19 2013 16:28:03 GMT-0400 (Eastern Daylight Time) has no method 'now' console.log(dd1.getTime()); console.log(Date.now()); //console.log(Date.getTime()); //Throws error ->TypeError: Object function Date() { [native code] } has no method 'getTime'

此区别是否有正式名称?这是静态"和非静态"之间的区别吗?当我创建Date的新实例时,是否应该继承所有方法?

Is there a formal name for this difference? Is this the difference between "static" and "non-static." When I create a new instance of Date, shouldn't all methods be inherited?

推荐答案

这是构造函数对象的属性与构造函数对象的原型的属性之间的差异."now"属性是Date构造函数本身的属性,而不是 Date.prototype 的属性.对于"getTime",情况恰恰相反.

It's the difference between properties of the constructor object and properties of the constructor object's prototype. The "now" property is a property of the Date constructor itself, and not a property of Date.prototype. It's the opposite situation for "getTime".

从语义上讲,这是有道理的:"now"的概念独立于任何特定的日期实例."getTime"方法旨在报告特定日期实例实际代表的日期的时间戳.

Semantically it makes sense: the concept of "now" is independent of any particular date instance. The "getTime" method is intended to report on the timestamp for the date actually represented by a particular date instance.

如果您要定义自己的构造函数,则可以这样创建类方法"(我个人会很犹豫地称呼它们,但无论如何):

If you're defining your own constructors, you can create "class methods" (I personally would hesitate to call them that, but whatever) like this:

function MyConstructor() { // ... } MyConstructor.someMethod = function() { // ... }

然后 MyConstructor.someMethod()调用该函数,而与您的类的任何特定实例无关.

Then MyConstructor.someMethod() calls that function independently of any particular instance of your class.

更多推荐

Date.getTime()与Date.now()

本文发布于:2023-10-24 02:54:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1522732.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Date   getTime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!