Let’s first look at some test codes like this to see what problems we can find:
var str=”likeke”;
str;//”likeke”
str.length;//6
str.age=22 ;
str.age;//undefined;
var mystr=new String("likeke");
mystr;//String {0: "l", 1: "i", 2: "k ", 3: "e", 4: "k", 5: "e", length: 6, [[PrimitiveValue]]: "likeke"}
mystr.length;//6
mystr.age=22 ;
mystr.age;//22
First question: Why can the basic type string access the length attribute?
Second question: The wrapper type of string can access custom attributes, but the basic type Why can't string be accessed?
Reason: 1. When we access a basic type string attribute in the form of an object or create a new attribute for it, the js engine will convert it into the corresponding packaging type object;
2. When we add a self- After defining the properties, the temporary object will be destroyed immediately. Therefore, accessing this property again (which will also be converted to its wrapping type again) appears as undefind .
In addition to string, other basic types have similar principles, for example, (666).toString().length;//3