Talking about JS packaging object

Time:2022-6-13
catalogue
  • summary
    • definition
    • Instance method
    • Automatic conversion between original type and instance object
    • Custom method
  • Boolean object
    • summary
    • Type conversion of Boolean function
  • Number object
    • summary
    • Static properties
    • Instance method
    • Custom method
  • String object
    • summary
    • Static method

summary

definition

Object is the main data type of JavaScript language. Under certain conditions, the values of the three original types – numeric value, string and Boolean value – will also be automatically converted into objects, that is, the “wrapper” of the original type.

The so-called “wrapper object” refers to the three native objects number, string and Boolean corresponding to numeric value, string and Boolean value respectively. These three native objects can transform (wrap) values of the original type into objects.


var v1 = new Number(123);
var v2 = new String('abc');
var v3 = new Boolean(true);

typeof v1 // "object"
typeof v2 // "object"
typeof v3 // "object"

v1 === 123 // false
v2 === 'abc' // false
v3 === true // false

In the above code, three corresponding wrapper objects are generated based on the value of the original type. You can see that V1, V2, and V3 are all objects and are not equal to the corresponding simple type values.

The design purpose of the wrapped object is to make the “object” type cover all the values of JavaScript. The whole language has a common data model. Secondly, the value of the original type can also call its own methods.

The three native objects, number, string, and Boolean, are often used to convert values of any type into numeric, string, and Boolean values if they are not called as constructors (that is, they are not added with new when called), but as ordinary function calls.

//String to numeric
Number('123') // 123

//Numeric to string
String(123) // "123"

//Numeric to Boolean
Boolean(123) // true

To sum up, when these three objects are used as constructors (with new), the value of the original type can be converted into an object; When used as a normal function (without new), you can convert any type of value to the value of the original type.

Instance method

Each of the three wrapper objects provides many instance methods. Here are two methods that they share and inherit from object objects: valueof() and tostring().

valueOf()

The valueof () method returns the value of the original type corresponding to the wrapper object instance.


new Number(123).valueOf()  // 123
new String('abc').valueOf() // "abc"
new Boolean(true).valueOf() // true

toString()

The toString () method returns the corresponding string form.


new Number(123).toString() // "123"
new String('abc').toString() // "abc"
new Boolean(true).toString() // "true"

Automatic conversion between original type and instance object

In some cases, the value of the original type will be automatically called as a wrapper object, that is, the properties and methods of the wrapper object will be called. At this time, the JavaScript engine will automatically convert the value of the original type into a wrapper object instance, and destroy the instance immediately after use.

For example, a string can call the length attribute to return the length of the string.


'abc'.length // 3

In the above code, ABC is a string, which is not an object itself. You cannot call the length attribute. The JavaScript engine automatically turns it into a wrapper object, and calls the length attribute on this object. After the call, the temporary object will be destroyed. This is called the automatic conversion between the original type and the instance object.

var str = 'abc';
str.length // 3

//Equivalent to
var strObj = new String(str)
// String {
//   0: "a", 1: "b", 2: "c", length: 3, [[PrimitiveValue]]: "abc"
// }
strObj.length // 3

The wrapper object generated by automatic conversion is read-only and cannot be modified. Therefore, the string cannot add a new attribute.


var s = 'Hello World';
s.x = 123;
s.x // undefined

The above code adds an X attribute to the string s, and the result is invalid. It always returns undefined.

On the other hand, the wrapper object instance is automatically destroyed after the call. This means that the next time a string attribute is called, a newly generated object is actually called instead of the object generated in the previous call, so the attribute assigned to the previous object cannot be obtained. If you want to add a property to a string, you can only add a property in its prototype object string Defined on prototype.

Custom method

In addition to the native instance methods, the wrapper object can also customize methods and properties, which can be called directly by the values of the original type.

For example, we can add a double method to double strings and numbers.


String.prototype.double = function () {
  return this.valueOf() + this.valueOf();
};

'abc'.double() // abcabc

Number.prototype.double = function () {
  return this.valueOf() + this.valueOf();
};

(123).double() // 246

The above code has customized a method on the prototype of string and number objects respectively, so that it can be called on all instance objects. Note that parentheses must be added outside the last 123, otherwise the following dot operator (.) Will be interpreted as a decimal point.

Boolean object

summary

A Boolean object is one of the three wrapper objects for JavaScript. As a constructor, it is mainly used to generate a wrapper object instance of a Boolean value.


var b = new Boolean(true);
typeof b // "object"
b.valueOf() // true

The variable B in the above code is an instance of a Boolean object. Its type is an object and its value is the Boolean value true.

Note that the Boolean operation result of the wrapper object instance corresponding to false is also true.

if (new Boolean(false)) {
  console.log('true');
} // true

if (new Boolean(false).valueOf()) {
  console.log('true');
}// no output

The first example in the above code gets true because the wrapper object instance corresponding to false is an object, which is automatically converted to the Boolean value true (because the Boolean values corresponding to all objects are true) during logical operations. The valueof method of the instance returns the original value corresponding to the instance. This example is false.

Type conversion of Boolean function

In addition to being a constructor, Boolean objects can also be used alone to convert arbitrary values to Boolean values. At this time, Boolean is a simple tool method.


Boolean(undefined) // false
Boolean(null) // false
Boolean(0) // false
Boolean('') // false
Boolean(NaN) // false

Boolean(1) // true
Boolean('false') // true
Boolean([]) // true
Boolean({}) // true
Boolean(function () {}) // true
Boolean(/foo/) // true

Several cases of getting true in the above code are worth remembering carefully.

By the way, use the double no operator (!) You can also convert any value to the corresponding Boolean value.


!!undefined // false
!!null // false
!!0 // false
!!'' // false
!!NaN // false

!!1 // true
!!'false' // true
!![] // true
!!{} // true
!!function(){} // true
!!/foo/ // true

Finally, for some special values, if you add new to the Boolean object, you will get the opposite result. You must be careful.

if (Boolean(false)) {
  console.log('true');
}// no output

if (new Boolean(false)) {
  console.log('true');
} // true

if (Boolean(null)) {
  console.log('true');
}// no output

if (new Boolean(null)) {
  console.log('true');
} // true

Number object

summary

The number object is a wrapper object corresponding to a number. It can be used as a constructor or as a tool function.

As a constructor, it is used to generate objects with numeric values.


var n = new Number(1);
typeof n // "object"

In the above code, the number object is used as a constructor to return an object with a value of 1.

As a tool function, it can convert any type of value to a numeric value.


Number(true) // 1

Static properties

The number object has the following static properties (that is, properties defined directly on the number object rather than on the instance).

  • Number. POSITIVE_ Infinity: positive infinity, pointing to infinity.
  • Number. NEGATIVE_ Infinity: negative infinity, pointing to -infinity.
  • Number. Nan: indicates a non numeric value, pointing to Nan.
  • Number. MIN_ Value: indicates the smallest positive number (that is, the positive number closest to 0, 5e-324 in the 64 bit floating-point number system). Correspondingly, the negative number closest to 0 is -number MIN_ VALUE。
  • Number. MAX_ SAFE_ Integer: represents the maximum integer that can be accurately represented, i.e. 9007199254740991.
  • Number. MIN_ SAFE_ Integer: represents the smallest integer that can be accurately represented, that is -9007199254740991.

Number.POSITIVE_INFINITY // Infinity
Number.NEGATIVE_INFINITY // -Infinity
Number.NaN // NaN

Number.MAX_VALUE // 1.7976931348623157e+308
Number.MAX_VALUE < Infinity // true

Number.MIN_VALUE // 5e-324
Number.MIN_VALUE > 0 // true

Number.MAX_SAFE_INTEGER // 9007199254740991
Number.MIN_SAFE_INTEGER // -9007199254740991

Instance method

The number object has four instance methods, all of which are related to converting a numeric value to a specified format.

Number.prototype.toString()

The number object deploys its own toString method to convert a value into a string.


(10).toString() // "10"

The toString method can accept a parameter that represents the output base. If this parameter is omitted, the value will be converted to decimal by default, and then the string will be output; Otherwise, a number will be converted into a string of base according to the base specified by the parameter.


(10).toString(2) // "1010"
(10).toString(8) // "12"
(10).toString(16) // "a"

In the above code, 10 must be placed in parentheses, which indicates that the following point represents the calling object attribute. If you do not add parentheses, this point will be interpreted as a decimal point by the JavaScript engine and an error will be reported.


10.toString(2)
// SyntaxError: Unexpected token ILLEGAL

As long as the JavaScript engine can not confuse the decimal point with the dot operator of the object, all kinds of writing methods can be used. In addition to adding parentheses to 10, you can also add two points after 10. JavaScript will understand the first point as a decimal point (that is, 10.0) and the second point as a calling object attribute, so as to get the correct result.

10..toString(2) // "1010"

//Other methods include
10 .toString(2) // "1010"
10.0.toString(2) // "1010"

This actually means that you can use the toString method directly on a decimal.


10.5.toString() // "10.5"
10.5.toString(2) // "1010.1"
10.5.toString(8) // "12.4"
10.5.toString(16) // "a.8"

The toString method can also be called through the square bracket operator.


10['toString'](2) // "1010"

The toString method can only convert a decimal number to a string of other bases. If you want to convert other base numbers back to decimal, you need to use the parseInt method.

Number.prototype.toFixed()

The ToFixed () method first converts a number to a specified number of decimal places, and then returns the string corresponding to the decimal place.


(10).toFixed(2) // "10.00"
10.005.toFixed(2) // "10.01"

In the above code, 10 and 10.005 are first converted to 2 decimal places, and then to a string. Of which 10 must be placed in brackets, otherwise the following point will be treated as a decimal point.

The parameter of the tofixed() method is the number of decimal places. The valid range is 0 to 20. If the range is exceeded, a rangeerror error will be thrown.

Due to the floating-point number, the rounding of decimal number 5 is uncertain, so you must be careful when using it.


(10.055).toFixed(2) // 10.05
(10.005).toFixed(2) // 10.01

Number.prototype.toExponential()

The toexponential method is used to convert a number to the form of scientific counting.


(10).toExponential()  // "1e+1"
(10).toExponential(1) // "1.0e+1"
(10).toExponential(2) // "1.00e+1"

(1234).toExponential()  // "1.234e+3"
(1234).toExponential(1) // "1.2e+3"
(1234).toExponential(2) // "1.23e+3"

The parameter of the toexponential method is the number of significant digits after the decimal point. The range is 0 to 20. Beyond this range, a rangeerror error will be thrown.

Number.prototype.toPrecision()

The toprecision method is used to convert a number to a valid number of specified digits.


(12.34).toPrecision(1) // "1e+1"
(12.34).toPrecision(2) // "12"
(12.34).toPrecision(3) // "12.3"
(12.34).toPrecision(4) // "12.34"
(12.34).toPrecision(5) // "12.340"

The parameter of the toprecision method is the number of significant digits. The range is 1 to 21. If the range is exceeded, a rangeerror error will be thrown.

The toprecision method is not reliable for rounding, which is related to the fact that floating-point numbers are not stored accurately.


(12.35).toPrecision(3) // "12.3"
(12.25).toPrecision(3) // "12.3"
(12.15).toPrecision(3) // "12.2"
(12.45).toPrecision(3) // "12.4"

Custom method

Like other objects, number You can customize the methods on the prototype object, which are inherited by the instance of number.


Number.prototype.add = function (x) {
  return this + x;
};

8['add'](2) // 10

The above code defines an add method for the number object instance. When a method is called on a value, the value will be automatically converted to the instance object of number, so you can call the add method. Since the add method returns a numeric value, it can be chain operated.


Number.prototype.subtract = function (x) {
  return this - x;
};

(8).add(2).subtract(4) // 6

We can also deploy more complex methods.


Number.prototype.iterate = function () {
  var result = [];
  for (var i = 0; i <= this; i++) {
    result.push(i);
  }
  return result;
};

(8).iterate() // [0, 1, 2, 3, 4, 5, 6, 7, 8]

The above code deploys the iterate method on the prototype of the number object to automatically traverse a value into an array.

Note that the custom method of a value can only be defined in its prototype object number On the prototype, the value itself cannot be customized.


var n = 1;
n.x = 1;
n.x // undefined

In the above code, n is a value of primitive type. Add an attribute x directly on it. No error will be reported, but it has no effect. It always returns undefined. This is because once the attribute is called, n is automatically converted to an instance object of number. After the call, the object is automatically destroyed. Therefore, the next time you call the attribute of N, you will actually get another object. Of course, attribute x cannot be read out.

String object

summary

String object is one of the three wrapper objects provided by JavaScript natively to generate string objects.


var s1 = 'abc';
var s2 = new String('abc');

typeof s1 // "string"
typeof s2 // "object"

s2.valueOf() // "abc"

A string object is an array like object (much like an array, but not an array).


new String('abc')
// String {0: "a", 1: "b", 2: "c", length: 3}

(new String('abc'))[1] // "b"

In the above code, the string object corresponding to the string ABC has numeric keys (0, 1, 2) and length attributes, so it can be valued like an array.

In addition to being used as a constructor, a string object can also be used as a tool method to convert any type of value to a string.


String(true) // "true"
String(5) // "5"

Static method

String.fromCharCode()

The static methods provided by the string object (that is, the methods defined in the object itself rather than in the object instance) are mainly string fromCharCode()。 The parameter of this method is one or more numeric values, representing Unicode code points, and the return value is the string composed of these code points.


String.fromCharCode() // ""
String.fromCharCode(97) // "a"
String.fromCharCode(104, 101, 108, 108, 111) // "hello"

In the above code, string If the parameter of the fromcharcode method is empty, an empty string is returned; Otherwise, the Unicode string corresponding to the parameter is returned.

Note that this method does not support characters with Unicode code points greater than 0xFFFF, that is, the passed in parameters cannot be greater than 0xFFFF (i.e. 65535 decimal).


String.fromCharCode(0x20BB7) // "ஷ"
String.fromCharCode(0x20BB7) === String.fromCharCode(0x0BB7)
// true

In the above code, string The fromcharcode parameter 0x20bb7 is greater than 0xFFFF, resulting in an error in the returned result. 0x20bb7 the corresponding characters are Chinese characters

The above is about the details of JS wrapper objects. For more information about JS wrapper objects, please pay attention to other developeppaer related articles!

Recommended Today

Network counting experiment I Division VLAN

Experiment 1  vlanCreation and division of 1、 Experiment purpose: 1. Understand the working principle of VLAN; 2. Learn the method of dividing VLANs based on ports; 3. Understand the communication between the same VLANs across switches; 4. Further learn the configuration commands of switch ports. 2、 Experimental principle: VLAN (virtual local area network), that is, […]