gpt4 book ai didi

javascript - 你将如何在 JavaScript 中编写 Date 对象?

转载 作者:行者123 更新时间:2023-11-29 19:55:58 24 4
gpt4 key购买 nike

Date 对象可能很好地说明了如何在 JavaScript 中创建对象。它的方法太多,无法成为一个简洁的示例,但我想看看如何构建这样一个对象的框架。

让我们假设有一个裸机值称为 ClockTick 或类似的东西,它返回毫秒。

因此 Date 对象同时用作 getter:

function Date() {
return ClockTick;
}

和一个二传手:

function Date(milliseconds) {
}

重载:

function Date(year, month, day, hours, minutes, seconds, milliseconds) {
}

问:如果不详尽,假设没有内置日期对象,您将如何用 JavaScript 编写 Date 对象?

最佳答案

对于您给出的基本示例,您基本上想要检查两件事:

  1. Date 是用new 作为构造函数调用,还是直接调用。
  2. 传递了多少参数。

我可能会这样做:

function Date(year, month, day, hours, minutes, seconds, milliseconds){
if (!(this instanceof Date)){
// If 'this' is not a Date, then the function was called without 'new'.
return /* current date string */
}
if (arguments.length === 0) {
// Populate the object's date with current time
} else if (arguments.length === 1){
// Populate the object's date based on 'arguments[0]'
} else {
// Populate the object's date based on all of the arguments
}
}

至于表示实际日期值,这完全取决于您。仅定义了外部接口(interface),因此您可以将其存储为时间戳,或日/月/年等的单独值。

在存储值方面,您有几个选择:

  1. 您可以将值存储在 this 本身,并将 Date 的所有方法添加到 Date.prototype 中。这种方法可能更快,因为函数都在原型(prototype)上共享,所以它们不会被重新创建,但这意味着值必须存储在 this 上,这意味着它们将对使用的人公开可见你的类(class)。

  2. 您可以将值存储在日期构造函数内的第二个对象上,然后将所有 Date 函数分配给构造函数内的 this,捕获一个对日期值对象的引用。这有隐藏内部值的好处,但意味着您需要为创建的每个新 Date 对象重新创建函数。

例如

function Date(...){
this.dayPrivate = day;
}

Date.prototype.getDay = function(){
return this.dayPrivate;
};

对比

function Date(...){
this.getDay = function(){
return day;
};
}

关于javascript - 你将如何在 JavaScript 中编写 Date 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16123034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com