Date.getTime()与Date.now() [英] Date.getTime() v.s. 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!