This article has participated in the Denver Nuggets Creators Camp 3 “More Productive writing” track, see details: Digg project | creators Camp 3 ongoing, “write” personal impact
preface
Do you want to know what packaging class is?
Or what methods and properties are defined on the wrapper class prototype?
This article will help you sort things out and manually wrap common wrapper class methods
explore
Let’s start with a phenomenon:
var str = "hello" ;
console.log(str.length) ;/ / 5
Copy the code
Defines a string variable STR, string calls a length property, print out the length of the string!
Do you wonder? Strings are primitive values, primitive values shouldn’t have attributes in them, right?
Indeed, objects have properties and methods!
What’s going on up there?
You’ve probably heard the phrase “everything in JavaScript is an object.” Arrays and functions are not the only objects. Primitive values we know (values, strings, bools) can also be converted into objects under certain conditions. Such objects are called “wrapper objects”.
So, the above code can be implemented because: when calling the original value of the properties and methods, JS found that the original value has no properties and methods, how do you call? In order not to report an error, it secretly changes the original type into a wrapper object, calls the properties and methods of the newly created wrapper object, and secretly deletes the object after execution.
Here’s an example:
var num = 3;
num.len = 2;
//new Number(3).len =2; delete
console.log(num.len);//endefined redefines the new Number(3).len
var str = "abcd";
str.length = 2;
//new String('abcd).length = 2; delete;
console.log(str);//abcd
console.log(str.length);// new String('abcd '); Note: Length is a built-in property of the string system. So return 4
Copy the code
As you can see from the above example, each call surreptitiously creates a new object, which has no relation to the previous object because it is deleted every time it is executed. So the life cycle of the wrapped class object is very short, making it pointless to add custom properties and methods to the wrapped class!
A wrapper class is a function. When a primitive value calls a property or method, it triggers a mechanism that, without your knowledge, passes the primitive value to the corresponding function and constructs the corresponding object. This process has the meaning of packaging, packaging, that you give me a raw value, I give you an object. That’s why they call these functions wrapper classes. Anyway, it’s just a name, so remember it.
There you have it!
Let’s take a look at what kinds of packaging there are.
A wrapper class
Number, String, and Boolean are the wrapper classes for the three primitive values
Let’s start with the first two simple ones: Number and Boolean
Number
If Number is not a Number, it will still be a Number: NaN;
console.log(Number(true))/ / 1
console.log(Number("hello"))//NaN
Copy the code
Wrapper objects generated by new Number() can inherit properties and methods from the Number prototype chain, including those on number.prototype and Object.prototype
Number. Prototype
Check out what’s on offer:
- Constructor: Returns the prototyped Number(){}
- ToExponential method: A form of scientific notation that returns a number
- ToFixed: Converts a number to a decimal number with a specified number of digits, and returns the ** corresponding to that decimal number
string
* * is as follows:
- ToLocaleString method: returns a number converted to a local string
- ToPrecision method: used to convert a number to a specified number of significant digits, return a string! []
- ToString: returns a string of numbers; Note that toString is not an Object
- ValueOf method: used to return the raw numeric valueOf a Number object
The Number constructor itself has static attributes (through Number). Directly called) which are:
- MAX_VALUE: indicates the maximum number that can be represented
- MIN_VALUE: the smallest number that can be represented
- NEGATIVE_INFINITY: negative infinity, which is returned when overflow occurs
- NaN: the number
- POSITIVE_INFINITY: positive infinity, which is returned when overflow occurs
- Prototype: prototype attribute; You can add properties and methods to the stereotype
Boolean
Boolean returns true or false when the Boolean function itself is called
The Boolean prototype also has only one property constructor and two methods:
- ToString method: returns a Boolean value as a string
- ValueOf: returns the original Boolean valueOf a Boolean object
Boolean and Number are very few things. Here’s the big brother in the wrapper class: String
The String method we’re always talking about comes from string.prototype
First, the normal use of String() itself is to convert data of any type to a String
- The value becomes a numeric string
- A string is a string
- Boolean values true for “true” and false for “false”
- Undefined and null become the corresponding strings “undefined” and “null”.
String
Let’s see how many properties and methods the new String produces inherit from the prototype:
Don’t doubt, don’t be surprised, there are just so many! Why else would you call it Big Brother
Don’t panic, the following common methods will be covered one by one:
- Length property: Returns the length of the string
- CharAt method: returns a character at the specified position; The position starts at zero
- CharCodeAt method: Returns the Unicode encoding of the character at the specified position
- Concat method: Similar to concat in arrays, concat is used to concatenate two strings, returning the new string without changing the original string
- Slice method: similar to slice in arrays, used to return a substring from the original string without changing the original string; The rules for passing parameters are exactly the same as for slice in arrays:
Use to intercept a substring from the original string and return it without changing the original string.
When there are two arguments: the first is the start bit and the second is the end bit (excluding the position)
If there is only one parameter: : Indicates that the bits are intercepted and returned
When no argument is passed: the entire string is truncated, which can be interpreted as copying the same value
If the argument is negative: indicates from the reciprocal position
If the first argument is greater than the second, such as slice(3,1), the method returns an empty string
-
Substring method: It also uses substrings from the original string and returns them, but there are some strange rules, so many people don’t recommend using this method in favor of slice.
-
The substr method returns a substring from the original string. The rule is a bit like splice in arrays:
If there are two arguments: the first argument represents the start bit, and the second argument represents the length of the truncated substring
If there is only one parameter: : indicates that the string is truncated from the start bit to the end of the original string
If the first argument is negative: indicates the character position of the reciprocal calculation
If the second argument is negative, it is automatically converted to 0 that is, truncated 0 bits, so an empty string is returned
- IndexOf() and lastIndexOf() : Similar to the indexOf and lastIndexOf arrays in ES5, this function is used to find the position of a specified string in the original string, and returns -1 if none is found
IndexOf matches from the head of the string, and lastIndexOf matches from the tail
When the second argument is accepted, the second argument of indexOf indicates a backward match from that position; The second parameter lastIndexOf indicates a forward match from that position
- Trim () : Removes whitespace at both ends of a string. Returns a new string without whitespace
- ToLowerCase () : returns a string that converts all strings toLowerCase without changing the original string
- ToUpperCase () : Returns a string that is fully capitalized without changing the original string
- LocaleCompare () : Compares the Unicode encoding size of two strings, returns 1 if the first is greater than the second, -1 if the first is less than the second, and 0 if the first is equal
- Match () : Matches whether the original string has a substring by the re, returning an array of the first string to be matched. If no match is found, null is returned
- Search () : Looks for a string in a string. The return value is the first position matched. If no match is found, -1 is returned.
- Replace () : A substring used to replace a match, usually only the first match (unless a regular expression with a G modifier is used)
- Split () : Splits a string into an array with the specified delimiter. By what split, what is gone
- Includes: checks whether a character contains anything, returning true or false
- StartsWith: checks whether it startsWith a string and returns true or false
- EndsWith: checks whether it endsWith a string and returns true or false
- Repeat () : Returns a string that repeats the connection a specified number of times
- TrimLeft () and trimStart(): Remove left Spaces
- TrimRight () and trimEnd(): Remove Spaces on the right
- There are many ways to return a string containing the corresponding HTML tag. Note: This may not be supported in some browsers
One last look at static properties and methods on String. If you are interested, try it yourself:
That’s the summary of the packaging class!