background

In the last article we mentioned that basic data types cannot add properties or methods which means that there are no properties or methods for basic data types; But strings, numbers, and booleans can all call properties and methods, such as:

const str = '123';
console.log(typeof(str)); // string
console.log(str.toString()); / / 123
console.log(str.length); / / 3
const num = 123console.log(typeof(num)); // number
console.log(num.toString()); / / 123
const bool = true;
console.log(typeof(bool)); // boolean
console.log(bool.toString()); // true
Copy the code

The Number, String, and Boolean types can call methods. So why is that? Look down.

define

JS Value, String, Boolean value corresponding to the Number, String, Boolean three native objects. These three native objects transform values of primitive types into (wrapped) objects. That’s the wrapper object of the primitive type.

var str = new String('asd'); // String {"asd"}
var num = new Number('123'); // Number {123}
var bool = new Boolean(true); // Boolean {true}

console.log(typeof(str)) // object
console.log(typeof(num)) // object
console.log(typeof(bool)) // object

str === 'asd' // false
num === 123 // false
bool === true // false
Copy the code

The above code, based on the value of the original type, generates three corresponding wrapper objects. As you can see, STR, num, and bool are all objects and are not equal to their original type values.

Automatic conversion

When a property or method of type Number, String, or Boolean is called, the JavaScript engine automatically converts it into a wrapper object on which its property or method is called. When the call ends, the temporary object is destroyed. This is called an automatic conversion of the primitive type to the instance object.

conclusion

These three objects (Number, String, Boolean) can be used as constructors (with new) to convert values of the original type into objects; When used as a normal function (without new), you can convert a value of any type to a value of the original type.