在 Javascript 中,如果 Date 对象具有相同的 valueOf 和 getTime 方法,为什么它们同时具有?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9710136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:33:30  来源:igfitidea点击:

In Javascript why do Date objects have both valueOf and getTime methods if they do the same?

javascriptdate

提问by Attila Kun

MDN says that valueOfand getTimeare functionally equivalent. Why have two functions that do the very same thing?

MDN 说valueOfgetTime在功能上是等效的。为什么有两个函数做同样的事情?

回答by maerics

The Date.prototype.getTimemethod returns the number of milliseconds since the epoch (1970-01-01T00:00:00Z); it is unique to the Date type and an important method.

Date.prototype.getTime方法返回自纪元 (1970-01-01T00:00:00Z) 以来的毫秒数;它是 Date 类型所独有的,也是一个重要的方法。

The Object.prototype.valueOfmethodis used to get the "primitive value" of any object. For the Date class, it is convenient to use the "time" attribute (the value returned by getTime()) as its primitive form since it is a common representation for dates. Moreover, it lets you use arithmetic operators on date objects so you can compare them simply by using comparison operators (<, <=, >, etc).

Object.prototype.valueOf方法用于获取任何对象的“原始值”。对于 Date 类,使用“时间”属性(由 返回的值getTime())作为其原始形式很方便,因为它是日期的常见表示形式。此外,它可以让您使用日期对象的算术运算符,所以你可以简单地通过使用比较操作符(对它们进行比较<<=>,等)。

var d = new Date();
d.getTime(); // => 1331759119227
d.valueOf(); // => 1331759119227
+d; // => 1331759119227 (implicitly calls "valueOf")
var d2 = new Date();
(d < d2); // => true (d came before d2)

Note that you could implement the "valueOf" method for your own types to do interesting things:

请注意,您可以为自己的类型实现“valueOf”方法来做一些有趣的事情:

function Person(name, age) {this.name=name; this.age=age;}
Person.prototype.valueOf = function() {return this.age; }

var youngster = new Person('Jimmy', 12);
var oldtimer = new Person('Hank', 73);
(youngster < oldtimer); // => true
youngster + oldtimer; // => 85

回答by csikosjanos

There are no difference in behaviour between those two functions:

这两个函数之间的行为没有区别:

https://code.google.com/p/v8/codesearch#v8/trunk/src/date.js&q=ValueOf&sq=package:v8&l=361

https://code.google.com/p/v8/codesearch#v8/trunk/src/date.js&q=ValueOf&sq=package:v8&l=361

// ECMA 262 - 15.9.5.8
function DateValueOf() {
  return UTC_DATE_VALUE(this);
}

// ECMA 262 - 15.9.5.9
function DateGetTime() {
  return UTC_DATE_VALUE(this);
}

But there are historical differences.

但存在历史差异。

回答by Rocket Hazmat

valueOfis a method of all objects. Objects are free to override this to be what they want.

valueOf是所有对象的方法。对象可以自由地将其覆盖为他们想要的。