Why are there two kinds of JavaScript strings?

前端 未结 3 403
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 06:47

This one just stabbed me hard. I don\'t know if it\'s the case with all browsers (I don\'t have any other competent browser to test with), but at least Firefox has two kind

3条回答
  •  天涯浪人
    2020-12-03 07:14

    There are two types of strings in Javascript -- literal strings and String objects. They do behave a little differently. The main difference between the two is that you can add additional methods and properties to a String object. For instance:

    var strObj = new String("object mode");
    strObj.string_mode = "object"
    strObj.get_string_mode = function() { return this.string_mode; }
    
    // this converts it from an Object to a primitive string:
    str = strObj.toString();
    

    A string literal is just temporarily cast to a String object to perform any of the core methods.

    The same kinds of concepts apply to other data types, too. Here's more on primitive data types and objects.

    EDIT

    As noted in the comments, string literals are not primitive strings, rather a "literal constant whose type is a built-in primitive [string] value", citing this source.

提交回复
热议问题