What's the point of new String(“x”) in JavaScript?

后端 未结 9 1819
走了就别回头了
走了就别回头了 2020-11-30 04:21

What are the use cases for doing new String(\"already a string\")?

What\'s the whole point of it?

9条回答
  •  生来不讨喜
    2020-11-30 05:23

    In most cases you work alone and can control yourself, or on a team and there is a team guideline, or can see the code you're working with, so it shouldn't be a problem. But you can always be extra safe:

    var obj = new String("something");
    typeof obj; // "object"
    
    obj = ""+obj;
    typeof obj; // "string"
    

    Update

    Haven't though much about the implications of this, although it seems to work:

    var obj = new String("something"), obj2 = "something else";
    obj.constructor === String; // true
    obj2.constructor === String; // true
    

    Of course, you should check if the object has a constructor (i.e. if it is an object).

    So you could have:

    isString(obj) {
       return typeof obj === "string" || typeof obj === "object" && obj.constructor === String;
    }
    

    Although I suggest you just use typeof and "string", a user should know to pass through a normal string literal.

    I should note this method is probably susceptible to someone creating an object and setting it's constructor to be String (which would indeed be completely obscure), even though it isn't a string...

提交回复
热议问题