Date 对象可以很好地说明如何在 JavaScript 中创建对象。 它的方法太多,无法成为一个简洁的示例,但我想看看如何构建这样一个对象的框架。
假设有一个名为 ClockTick 或类似值的裸机值,它返回毫秒。
因此 Date 对象既用作 getter:
function Date() {
return ClockTick;
}
和一个二传手:
function Date(milliseconds) {
}
重载:
function Date(year, month, day, hours, minutes, seconds, milliseconds) {
}
问:如果没有详尽说明,假设尚未内置 Date 对象,您将如何在 JavaScript 中编写 Date 对象?
最佳答案
对于您给出的基本示例,您基本上想要检查两件事:
Date
是通过new
作为构造函数调用,还是直接调用。- 传递了多少个参数。
我可能会做这样的事情:
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),因此您可以将其存储为时间戳,或日/月/年等的单独值。
在存储值方面,您有几个选项:
您可以将值存储在
this
本身上,并将Date
的所有方法添加到Date.prototype
上。这种方法可能会更快,因为这些函数都在原型(prototype)上共享,因此它们不会被重新创建,但这意味着这些值必须存储在this
上,这意味着它们对使用的人公开可见你的类(class)。您可以将值存储在日期构造函数内的第二个对象上,然后将所有
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/