JavaScript primitive types and corresponding objects

后端 未结 2 972
一个人的身影
一个人的身影 2020-12-03 04:09

In JavaScript not every data is an object. There exist a few primitive types, like strings, numbers and Boolean which are not objects. For each of these types there exists a

2条回答
  •  不知归路
    2020-12-03 04:18

    What is the advantage of keeping two separate representations?

    As you point out, you can call methods on unboxed values too (a.toFixed(1)). But that does cause a conversion. In other words, an instantiation of a new boxed object (probably) every time you call such a method.

    So there is a performance penalty right there. If you explicitly create a boxed Number and then call its methods, no further instances need to be created.

    So I think the reason for having both is much historical. JavaScript started out as a simple interpreted language, meaning performance was bad, meaning any (simple) way they could increase performance was important, such as making numbers and strings primitive by default.

    Java has boxed vs. unboxed values as well.

提交回复
热议问题