JavaScript primitive types and corresponding objects

后端 未结 2 958
一个人的身影
一个人的身影 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.

    0 讨论(0)
  • 2020-12-03 04:35

    What is the advantage of keeping two separate representations for numbers, strings and Booleans?

    Performance

    In what context could one need the distinction between primitive types and objects?

    Coercion comes to mind. 0 == false while new Number(0) != false

    So for instance:

    var a = new Boolean(false);
    if(a) {
      // This code runs
    }
    

    but

    var a = false;
    if(a) {
      // This code never runs
    }
    

    You can read more about coercion here: JavaScript Coercion Demystified

    0 讨论(0)
提交回复
热议问题