Basic packaging class

In order to facilitate primitive type manipulation, three special reference types are provided in JS: Boolean, Number, and String, which have primitive type special behavior. In fact, every time a primitive type is read, a primitive wrapper type object is automatically created inside JS, allowing us to call some methods to manipulate it.

Let STR = 'hello 'let str1 = str.substring(2)Copy the code

In example above, STR is a string, but it calls the substring method and stores the result in STR1. We know that the base type is not an object, so we wonder, “Gee, it’s not an object, why can we call a method?” The access process is in a read state, that is, the value of the string is read from memory. So what’s inside js? Look at the following.

  1. Create an instance of String
  2. Invokes the specified method on the instance
  3. Finally, the instance is destroyed
STR = new String('hello frogman ') let str1 = str.subString (2) str1 = nullCopy the code

After the above processing, the basic string becomes the same as the object. The above three steps also apply to Boolean and Number types.


What’s the difference between a reference type and a basic wrapper class? The main difference is the lifetime of the object.

  • Reference type: Instances of reference types created using the new operator are kept in memory until the execution flow leaves the current scope.
  • Basic wrapper type: there is only one line of code that is executed instantaneously and then destroyed immediately

The basic wrapper class means that we cannot add properties and methods to objects at run time because they are destroyed immediately after execution

Let STR = 'frogman' str.age = 23 console.log(str.age) // undefinedCopy the code

The age attribute is undefined in the second line of code. The age attribute is undefined in the third line of code.


If you think it’s good, give it a thumbs up!