In JavaScript, string, number, and boolean are all primitive types, that is, strings, numbers, and Boolean values do not exist in the form of objects. However, since these three primitive types of values need to be operated on, JavaScript will automatically encapsulate these three types of values and make them as objects with properties and methods. Taking string as an example, this encapsulation process is as follows:
1. When JavaScript encounters attribute access or method invocation of a string value, it will call new String (string value) to automatically encapsulate the string into a String object.
2. JavaScript will access the properties or methods of this newly created object and return the corresponding results.
3. After the attribute access or method call is completed, JavaScript will immediately destroy the newly created object.
Taking the following code as an example, it makes no sense to write properties to a String object automatically created by JavaScript, because the created object no longer exists after the writing statement ends:
It is worth noting that the s variable in the above code always represents a primitive string. The string object automatically created by JavaScript exists in the process of executing the s.length or s.newVariable operation. This can be verified from the last line of code in the above experiment.
In addition to automatically encapsulating Primitive values, developers can also choose to perform the corresponding process manually. Unlike automatic encapsulation, the object obtained by manual encapsulation will not be destroyed immediately, so the property writing operation taken for the manually encapsulated object is meaningful:
console.log(t == "test");//true
console.log(t === "test");//false