JavaScript 中惯用的“Number”对象到数字文字的转换
Number
函数
> var x = new Number(5)
> x === 5
false
> Number(x) === 5
true
valueOf
方法
> var y = new Number(5)
> y === 5
false
> y.valueOf() === 5
true
哪个是首选选项?使用其中一种比另一种有好处吗?
作为记录,我正在 Number.prototype
上的方法中处理 this
,在这里我可以确定 this
始终是 <代码>数字对象。
Number
function
> var x = new Number(5)
> x === 5
false
> Number(x) === 5
true
valueOf
method
> var y = new Number(5)
> y === 5
false
> y.valueOf() === 5
true
Which is the preferred option? Are there benefits to using one over the other?
For the record, I'm dealing with this
within a method on Number.prototype
, where I can be sure that this
is always a Number
object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为
valueOf
是首选,因为Number
转换旨在与还不是Number
对象的值一起使用,但此外 - < code>Number(x) 将调用x
上的valueOf
方法,因此本质上,您会添加不必要的糖/开销,其中
valueOf
是接收对象的原始表示形式的完全接受的方式(在您的情况下是Number
)。作为旁注:
这是不正确的,因为总是有可能有人会做这样的事情:
当然会提供:
作为输出。由您决定是否要防御它。
I would think the
valueOf
is preferred, sinceNumber
conversion is meant to be used with values that are not alreadyNumber
objects, but moreover -Number(x)
will callvalueOf
method onx
,so essentially, you'd add an unnecessary sugar/overhead, where
valueOf
is a perfectly accepted way of receiving a primitive representation of an object (Number
in your case).As a side note:
this is not correct as there is always a possibility that someone will do something like this:
would of course provide:
as output. It's for you to decide whether you want to defend against it.
为什么使用 Number 对象?我认为你只是让生活变得困难。要将 Number 对象转换为数字基元,您可以使用“+”运算符:
为了好玩:
Why are you using Number objects? I think you are just making life difficult. To convert a Number object to a number primitive you can use the '+' operator:
For fun: