我试图为日期对象定义一个新的吸气剂。但是,它返回false。我的错误在哪里?

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);

最佳答案

您一个多月前没有进行测试,因此它仅返回false,这是您||操作的最后一个值。

[...]
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

另外,__defineGetter__是非标准的并且已弃用,因此我在小提琴中将其替换为标准的原型方法属性。这是带有原始吸气剂的fiddle

编辑:ES5提供了标准的Object.defineProperty方法,请在下面的注释中查看@bfavaretto和@Bergi的版本:

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


原型方法似乎比defineProperty slightly faster,但是考虑到误差范围,在最新稳定的Chrome V8中,结果在60到2.3亿个OPs / sec之间变化,性能没有明显的差异。属性查找非常快,因此即使在Node环境中也不应有任何显着差异。

关于javascript - __defineGetter__函数始终返回false,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14508969/

10-11 06:33