2013-04-20 44 views
2

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

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

所以Date对象既用作一个getter:

function Date() { 
    return ClockTick; 
} 

和setter方法:

function Date(milliseconds) { 
} 

超载:

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

问:如果没有穷举,如何你会写在JavaScript中的日期对象,假设没有一个已经内置?

+0

JavaScript不支持在语言级别超载。你将不得不这样做 - http://ejohn.org/blog/javascript-method-overloading/。 – 2013-04-20 17:22:37

+1

虽然它使用了一些本地引用,但Google的V8 [DateConstructor'仍然有一个体面的例子](https://code.google.com/p/v8/source/browse/trunk/src/date.js#141) 。 – 2013-04-20 18:13:20

回答

3

你给基本的例子,你基本上要检查两件事情:

  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 
    } 
} 

至于代表实际日期值,这是真的取决于你。只有外部接口的定义,所以你可以将其存储为一个时间戳,或日/月/年独立值等

在存储值的方面,你有几种选择:

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

  2. 可以将值存储日期构造内的第二对象上,然后分配所有的Date功能集成到this构造内,捕捉到的时间值对象的引用。这具有隐藏内部值的好处,但意味着您需要重新创建每个新创建的对象的功能。

例如,

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

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

VS

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

感谢@loganfsmyth!当谈到“填充对象的日期”时,需要关闭,不是吗?如果一个闭包,那么函数内部的某种功能。 – 2013-04-20 18:27:19

+0

@Phillip:不,不是一个附加函数 - 构造函数已经足够关闭了。并且填充'Date'对象的内部值几乎不能用普通的JS表示 - 最接近的就是创建constand'valueOf'方法。 – Bergi 2013-04-20 18:58:37

相关问题