How to cache the JavaScript Date object?

旧街凉风 提交于 2019-12-23 17:07:55

问题


I am using Date.js to support many cultures in my web app. The problem here is that date.js has code like this.

  Date.prototype._toString = Date.prototype.toString;
  Date.prototype.toString = function () {
    //doing something
        return this._toString();
   }

when I use another culture file, it also contains this definition. so logically my doc has this

//date.js
     Date.prototype._toString = Date.prototype.toString;
     Date.prototype.toString = function () {
     //doing something
         return this._toString();
     }
     //date-fr-FR.js
     Date.prototype._toString = Date.prototype.toString;
     Date.prototype.toString = function () {
         //doing something
         return this._toString();
     }

I am refering to both date.js and date-fr-FR.js in my web app.

The problem is when I use the toString function var d = new Date().toString(); it throws an Out of stack space msg, because of the recursive calls. Is there any way to cache the orginal Date object and rest it back, because i don't want to remove date.js from doc


回答1:


Instead of including both date.js and date-fr-FR.js, you only need to include the fr-FR.js file to change the culture, which you will find in the src/globalization folder in the Datejs-all-Alpha1.zip file. The fr-FR.js file only contains the culture specific data, and it should override what is already included in date.js, without redefining the functionality.




回答2:


All you have to do is check whether _toString has been defined or not.

Date.prototype._toString = Date.prototype._toString || Date.prototype.toString;
Date.prototype.toString = function() {
    //doing something      
    return this._toString();
}



回答3:


You should only copy the function once:

Date.prototype._toString = Date.prototype.toString;

The second time you do this, it will copy the native toString function again, wich will then call itself via a recursive loop.

I don’t know if you are actually doing this more than once, bu in the fr-FR.js file there are no other toString methods defined so I’m guessing you are adding it manually.

Update

If you are including the date.js core twice (which you shouldn’t, just include the locales), you could probably check if the function is present first:

if ( typeof Date.prototype._toString != 'function' ) {
    // include date.js
}


来源:https://stackoverflow.com/questions/13173425/how-to-cache-the-javascript-date-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!