Strings are not object then why do they have properties?

前端 未结 5 2025
孤城傲影
孤城傲影 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 12:52

    Is string an object?

    This depends on how you defines object and what are you referring to when you say string. When you use the word string, you can be referring to just the primitive, or the wrapper object.

    What are primitives?

    In JavaScript there are 5 primitive types: undefined, null, boolean, string and number. Everything else is an object.

    Unlike objects, primitives don't really have properties. They exist as values. This explains why you cannot assign a property to a string:

    var archy = "hello";
    archy.say = "hello";
    console.log(archy.say); // undefined
    

    But sometimes manipulating a primitive would make one feel as if she/he is manipulating an object because primitives appear to have methods.

    var archy = "hello";
    console.log(archy.length); //5
    

    This is due to the fact that JavaScript creates a wrapper object when you attempt to access any property of a primitive.

    What are wrapper objects?

    Here is an extract from Javascript: The Definitive Guide

    The temporary objects created when you access a property of a string, number, or boolean are known as wrapper objects, and it may occasionally be necessary to distinguish a string value from a String object or a number or boolean value from a Number or Boolean object. Usually, however, wrapper objects can be considered an implementation detail and you don’t have to think about them. You just need to know that string, number, and boolean values differ from objects in that their properties are read-only and that you can’t define new properties on them.

提交回复
热议问题