The phenomenon of
When we try to add dynamic attributes to a string, it doesn’t work
1| let s = 'hero';
2| s.name = 'teemo';
3| console.log(s.name); // undefiend;
Copy the code
The above attempt to add attribute name to string S appears to be successful, but when it is read, it does not get.
Packing type
The main reason for this is that js does boxing when it reads strings. The resulting wrapper object has a special life cycle. For example, in the output statement above, the JS engine does the following three steps
console.log(s.name); // undefined
Copy the code
- Create an instance of String
- Read methods on instances
- Destroy instance
Console. log(s.name)
let s1 = new String('hero');
console.log(s1.name.toString());
Copy the code
‘teemo’ = ‘teemo’; The reason is that the second line of code creates a temporary String object when it runs, and when the third line of code executes, the object has already been destroyed. When the third line reads the string, it creates a new wrapper object that does not have the name attribute.
The main difference between reference types and raw value wrapper types is the life cycle of the object. After a reference type is instantiated with new, the resulting instance is destroyed when it leaves scope, and the automatically created raw value wrapper object exists only for the execution of the line of code that accessed it. This means that attributes and methods cannot be added to raw values at run time
Add attributes to strings
If you really want to add attributes to strings, you can define new attributes on String.prototype
String.prototype.name = 'teemo';
let s = 'hero';
console.log(s.name); // teemo
Copy the code
However, this is not recommended for general scenarios because it affects all strings. Similarly, Boolean and Number have the same properties as String.
Refer to the red book