0

I am trying to define a new getter for the date object. However it returns false. Where's my error?

Date.prototype.__defineGetter__('ago', function(){
    var diff = ((( new Date()).getTime() - this.getTime()) / 1000)
    , day_diff = Math.floor(diff / 86400);
    return day_diff == 0 && (
    diff < 60 && "just now" ||
    diff < 120 && "1 minute ago" ||
    diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
    diff < 7200 && "1 hour ago" ||
    diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
    day_diff == 1 && "Yesterday" ||
    day_diff < 7 && day_diff + " days ago" ||
    day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
});

var a = new Date('12/12/1990');
console.log(a.ago);
4

1 に答える 1

5

You didn't make a test for more than one month ago so it just returns false, which is the last value from your || operations.

[...]
day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago" ||
'More than a month ago';
[...]

var a = new Date('12/12/1990');
console.log(a.ago()); //More than a month ago

Fiddle

Also, __defineGetter__ is non-standard and deprecated so I've replaced it by a standard prototype method property in the fiddle. Here's the fiddle with the original getter.

edit: ES5 provides a standard Object.defineProperty method, see @bfavaretto and @Bergi's versions in the comments below:

Object.defineProperty(Date.prototype, "ago", {
    get: function() {
        [...]
    }
});

The prototype method seems slightly faster than defineProperty, however taking in consideration the error margin with results varying from 60 to 230 million OPs/sec in the latest stable Chrome's V8, there isn't a noticeable performance difference. Property lookups are extremely fast so there shouldn't be any notable difference even in a Node environment.

于 2013-01-24T19:32:33.767 に答える