Javascript “奇怪”;“吸气剂”;从数字文本访问'Number.prototype'属性时IE9中的行为
有人能解释这种行为和/或建议解决方法吗Javascript “奇怪”;“吸气剂”;从数字文本访问'Number.prototype'属性时IE9中的行为,javascript,properties,internet-explorer-9,getter,prototype-programming,Javascript,Properties,Internet Explorer 9,Getter,Prototype Programming,有人能解释这种行为和/或建议解决方法吗 我无法解释这个结果,但你也要求解决这个问题 演示: 脚本: Object.defineProperty(Number.prototype, 'foo', { get: function () { return this } }) console.log(10.5.foo) console.log(10..foo) // 0 in IE9! console.log(10.0.foo) // 0 in IE9! console.log(10.01.
我无法解释这个结果,但你也要求解决这个问题 演示: 脚本:
Object.defineProperty(Number.prototype, 'foo', {
get: function () { return this }
})
console.log(10.5.foo)
console.log(10..foo) // 0 in IE9!
console.log(10.0.foo) // 0 in IE9!
console.log(10.01.foo)
console.log((10).foo) // 0 in IE9!
var x = 10
console.log(x.foo) // 0 in IE9!
为了避免玷污API,可以在必须容纳IE9的上下文中定义帮助函数:
Number.prototype.foo = function() { return Number( this ) };
console.log(10.5.foo())
console.log(10..foo())
console.log(10.0.foo())
console.log(10.01.foo())
console.log((10).foo())
var x = 10
console.log(x.foo())
这允许:
function _(n) { return new Number(n) }
我很想知道一个更好的解决方法。只是出于好奇,你到底为什么要这样做?使用新的数字(10)-只使用整数作为原语失败。很好找到了!它看起来确实像一个IE9 bug,但我很好奇其背后的原因。。一定有更好的方法来做你想做的事情。@davidchambers,即使在IE10预览版上也会出现这个bug,如果你有空闲时间,我鼓励你这样做。干杯。刚刚关闭的已修复:“此问题已在2012年5月31日发布的Windows 8版本预览版上的Internet Explorer 10平台预览6中解决。”非常好!我现在正在为自己没想过要尝试这个而自责。哎呀。我不应该在下飞机后直接读代码。乍一看,我没有注意到
foo
在这里是一个方法,而不是一个属性。这当然是一种选择,但我希望找到一种不需要更改API的解决方法。@davidchambers:“方法”只是碰巧具有函数的属性type@LightnessRacesinOrbit:是的,但是我想能够写x.squared
而不是x.squared()
。那么Object.defineProperty呢(Number.prototype,'foo',{get:function(){returnnewnumber(this)}})
?
_(10).foo