JavaScript provides 5 raw data types: Number, String, Boolean, NULL, and undefined. For the first 3, number, String, and Boolean, the encapsulated object is provided with the constructor for number (), string (), and Boolean (). The following code shows the differences between the original data types and their encapsulated objects:
A primitive Numbervar n = 100;console.log (typeof N); "Number"//a number Objectvar Nobj = new number, Console.log (typeof nobj); "Object"
Encapsulating objects provides many useful features, such as the number object provides methods such as tofixed () and Toexponential (), String objects provide substring (), charAt (), T, and toLowerCase () Method and the Length property. But the original data types can also call these methods, because when you try to invoke these methods on an original data type, JavaScript's runtime environment automatically converts them into encapsulated objects:
A primitive string is used as an objectvar s = "Hello"; Console.log (S.touppercase ()); "HELLO"//The value itself can act as an object "monkey". Slice (3, 6); "Key"//Same for numbers (22/7). toprecision (3); "3.14"
Since the original data type can do the work of encapsulating objects, we do not need to new the encapsulated object in the code: because the JavaScript runtime environment helps us to convert them automatically when needed. There is less need to even encapsulate objects in the actual work, and it is only necessary to add its own "properties" to the original data type in order to have the new package object. Because if you can't directly use a property of the original data type:
Primitive Stringvar greet = "Hello there";//primitive-converted-an object//in order-to-use the split () METHODGR Eet.split (") [0]; "Hello"//attemting to augment a primitive are not a errorgreet.smile = true;//but it doesn ' t actually worktypeof gree T.smile; "Undefined"
Finally, if you do not use new to execute the constructor of the encapsulated object, they will help you to convert the parameters to an original data type:
typeof number (1); "Number" typeof number ("1"); "Number" typeof number (new number ()); "Number" typeof String (1); "String" typeof Boolean (1); "Boolean"
Wrapper objects for JavaScript base raw data type (Primitive Wrapper object)