In JavaScript, string, number, and boolean are all primitive basic types, that is, strings, numerical values, and boolean values do not exist in the form of objects. However, since these three primitive types need to be operated on, JavaScript will automatically encapsulate these three types of values so that they have properties and methods as objects. Taking string as an example, this encapsulation process is as follows:
1. When JavaScript encounters property access or method calls to string values, new String (string value) will be called to automatically encapsulate the string into a String object.
2. JavaScript will access the properties or methods of the newly created object and return the corresponding result.
3. After the property access or method call is completed, JavaScript will immediately destroy the newly created object.
As an example, it is meaningless to write attributes to String objects automatically created by JavaScript, because the created object no longer exists after the write statement is finished:
The code copy is as follows:
var s = "test";
s.length = 9;
console.log(s.length);//still 4
s.newVariable = 9;
console.log(s.newVariable);//undefined
console.log(s === "test");//true
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 during the execution of s.length or s.newVariable operations. 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 manually perform the corresponding process. Unlike automatic encapsulation, the resulting objects obtained by manual encapsulation are not immediately destroyed, so the property write operations taken for manually encapsulated objects make sense:
The code copy is as follows:
var t = new String("test");
t.length = 9;
console.log(t.length);//still 4, as length attribute is read only
t.newVariable = 9;
console.log(t.newVariable);//9
console.log(t == "test");//true
console.log(t === "test");//false