In JavaScript, string, number, and Boolean are primitive basic types, and the string, numeric, and Boolean values do not exist in the form of objects. However, because the three primitive type values need to be manipulated, JavaScript automatically encapsulates these three types of values so that they have properties and methods as objects. Take string For example, this encapsulation process is as follows:
1. When JavaScript encounters a property access to a string value or a method call, a new string (string value) is invoked to automatically encapsulate the string into a string object.
2.JavaScript accesses the properties or methods of the newly created object and returns the corresponding result.
3. When the property is accessed or the method call ends, JavaScript destroys the newly created object immediately.
The following code, for example, does not make a property write operation for a string object created by JavaScript automatically, because the created object ceases to exist after the write statement:
Copy Code code 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 is always represented as a primitive string, and that JavaScript automatically creates string objects that exist in the process of performing s.length or s.newvariable operations. This can be validated from the last line of code in the above experiment.
In addition to the automatic encapsulation of the primitive value, developers can also choose to manually perform the appropriate process. Unlike automatic encapsulation, a manual encapsulation of the resulting object is not immediately destroyed, so the property write action for the manually encapsulated object makes sense:
Copy Code code 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