您的代碼正在嘗試致電getDate
作爲您將其添加到專業版的那一刻輸入。相反,你想稍後調用它,當這個屬性被訪問時。
您有兩種選擇:方法或帶有「getters」的屬性。在你的情況,我想只有一個方法:
Date.prototype.stdDate = function(part) {
switch (String(part).toLowerCase()) {
case "hour":
return Math.ceil(this.getTime()/(1000 * 3600));
case "day":
return Math.ceil(this.getTime()/(1000 * 3600 * 24));
case "week":
return Math.ceil(this.getTime()/(1000*3600*24*7));
case "year":
return Math.ceil(getTime()/(1000*3600*24*365.242));
default:
// What you think appropriate
}
};
注意,這裏我定義只是一個單功能,stdDate
,它接受一個字符串參數:
var hour = dt.stdDate("hour");
這是因爲如果我們將stdDate
引用到對象上並將方法放在對象上,則this
不會再引用該日期。 (有辦法解決這個問題,但它們比這裏可能需要的更麻煩)。
在ES5驅動的引擎上,製作dt.stdDate.Hour
和這樣的工作是可能的(但可能更麻煩)
// On the prototype, define a property called `stdDate` that has a getter
Object.defineProperty(Date.prototype, "stdDate", {
get: function() {
// This is the getter: Create an object with properties for
// Hour, Day, and such which have getters. The getters are
// "bound" to `this` using `Function#bind`:
var stdDate = {};
Object.defineProperties(stdDate, {
Hour: {
read: function() {
return Math.ceil(this.getTime()/(1000 * 3600));
}.bind(this),
},
Day: {
read: function() {
return Math.ceil(this.getTime()/(1000 * 3600 * 24));
}.bind(this),
},
Week: {
read: function() {
return Math.ceil(this.getTime()/(1000*3600*24*7));
}.bind(this),
},
Year: {
read: function() {
return Math.ceil(this.getTime()/(1000*3600*24*365.242));
}.bind(this)
}
});
// Now, redefine the `stdDate` property on this specific instance
Object.defineProperty(this, "stdDate", {
value: stdDate
});
// And return it
return stdDate;
}
});
(你可能要與鼓搗得到它完美的工作,我衝出來的,不能馬上進行調試,但這個想法是存在的。)
那是真的很費解並且可能不是一個好主意,但是如果API dt.stdDate.Hour
對您來說真的很重要,那麼可能是。
在日期對象上使用getTime。 var d = new Date; d.getTime() – Fyre 2014-10-26 14:52:07