我正在尝试创建自己的Date对象本地化版本。我知道有一个名为toLocaleDateString()
的方法,它有一个locale参数,例如为了显示阿拉伯语日历的日期,我们只需要设置语言环境参数:
.toLocaleDateString('ar-EG')
现在我的问题是如何覆盖此行为以显示我自己的日历及其语言环境格式?
答案 0 :(得分:2)
覆盖这样的原生方法被认为是非常糟糕的做法,但是因为你问过:
Date.prototype.toLocaleDateString = function () {
// Your custom function
}
var foo = new Date();
foo.toLocaleDateString();
答案 1 :(得分:2)
在JavaScript中我们使用原型,因此要覆盖此方法,您必须执行下一步:
Date.prototype.toLocaleDateString = // and your method
我希望它能帮到你
答案 2 :(得分:1)
看看这个例子是否有帮助。首先,我在自定义方法中保存了默认函数。然后覆盖默认方法进行交易。看:
Date.prototype.toLocaleDateStringDefault = Date.prototype.toLocaleDateString;
Date.prototype.toLocaleDateString = function(){
var options = {year: "numeric", month: "long", day: "numeric"};
var result = this.toLocaleDateStringDefault("pr-BR", options);
return result;
}
document.getElementsByTagName("div")[0].innerHTML = new Date().toLocaleDateString();
<div></div>