当getter返回函数时,Firefox中出现意外行为

时间:2011-10-21 06:52:13

标签: javascript this getter prototype-programming

Object.defineProperty(Number.prototype, 'foo', {
  get: function () {
    var me = this
    return function () { return me.valueOf() }
  }
})

console.log(5..foo())

这会在Chrome中记录5,但在Firefox中记录为0。

Object.defineProperty(Number.prototype, 'bar', {
  get: function () {
    return this.valueOf()
  }
})

console.log(5..bar)

这会在预期的两个浏览器中记录5个。

任何人都可以解释这种行为,也许可以建议如何将第一个示例重写为在Firefox中工作,就像在Chrome中一样?

jsfiddle.net/V2sHg/2/

1 个答案:

答案 0 :(得分:0)

使用“新号(值)”但不直接使用“数字”时,它适用于FF:

尝试:

var n = new Number(8);
n.foo(); --> 8