Strings are not object then why do they have properties?

前端 未结 5 2026
孤城傲影
孤城傲影 2020-12-19 12:42

Code like this:

var str = \"Hello StackOverflow !\";
alert(typeof str);

gives me string as result. This means strings are not

5条回答
  •  爱一瞬间的悲伤
    2020-12-19 13:01

    A string like "Hello" is not an object in JavaScript, but when used in an expression like

    "Hello".indexOf(2)
    

    A new object derived from the constructor function String is produced wrapping the string "Hello". And indexOf is a property of String.prototype so things work as expected, even though there is a lot of magic going on.

    In the following case

    > var s = "xyz"; s.prop = 1; console.log(s.prop);
    undefined
    

    The reason you see undefined is that:

    1. The variable s is given a value which is a primitive string
    2. In s.prop = 1 and property named prop is assigned to a new, anonymous wrapper object.
    3. In the third statment above, another new object is created to wrap the primitive s. That is not the same wrapper object as in the second statement, and it does not have a prop property, so undefined is produced when asking for its value according to the basic JavaScript rules.

提交回复
热议问题