ECMAScript Reference Types
- Previous Page ECMAScript Type Conversion
- Next Page Unary Operators
Reference types are usually called classes (class).
This tutorial will discuss a large number of pre-defined reference types in ECMAScript.
Reference types
Reference types are usually called classes (class), which means that when dealing with reference values, the object is being processed.
This tutorial will discuss a large number of pre-defined reference types in ECMAScript.
From now on, the focus will be on reference types closely related to the primitive types already discussed.
Note:In the traditional sense, ECMAScript does not truly have classes. In fact, there is no mention of the word 'class' at all in ECMA-262. ECMAScript defines 'object definition', which is logically equivalent to classes in other programming languages.
Tip:This tutorial will use the term "object".
Objects are created by the new operator followed by the name of the object to be instantiated. For example, the following code creates an instance of the Object object:
var o = new Object();
This syntax is similar to the Java language, but ECMAScript requires the use of parentheses when there are more than one parameter. If there are no parameters, as shown in the following code, parentheses can be omitted:
var o = new Object;
Note:Although parentheses are not required, it is best to use them to avoid confusion.
Tip:We will delve deeper into objects and their behaviors in the chapter on object basics.
The focus of this section is on reference types that have equivalent primitive types.
Object object
The Object object is not very useful on its own, but it is still necessary to understand it before understanding other classes. Because the Object object in ECMAScript is similar to java.lang.Object in Java, all objects in ECMAScript inherit from this object, and all properties and methods in the Object object will appear in other objects. Therefore, understanding the Object object can help better understand other objects.
The Object object has the following properties:
- constructor
- Reference (pointer) to the function that creates the object. For the Object object, this pointer points to the original Object() function.
- Prototype
- Reference to the object prototype of the object. For all objects, it defaults to returning an instance of the Object object.
The Object object also has several methods:
- hasOwnProperty(property)
- Determine whether the object has a specific property. The property must be specified as a string. (For example, o.hasOwnProperty("name")}
- IsPrototypeOf(object)
- Determine whether the object is the prototype of another object.
- PropertyIsEnumerable
- Determine whether the given property can be enumerated using the for...in statement.
- ToString()
- Return the original string representation of the object. For the Object object, ECMA-262 does not define this value, so different ECMAScript implementations may have different values.
- ValueOf()
- Return the original value that is most suitable for the object. For many objects, the value returned by this method is the same as the value returned by ToString().
Note:Each property and method listed above will be overridden by other objects.
Boolean object
The Boolean object is a reference type of the Boolean primitive type.
To create a Boolean object, simply pass a Boolean value as a parameter:
var oBooleanObject = new Boolean(true);
The Boolean object overrides the ValueOf() method of the Object object, returning the primitive value, i.e., true and false. The ToString() method is also overridden, returning the string "true" or "false".
Unfortunately, Boolean objects are rarely used in ECMAScript, and even when used, they are not easy to understand.
Problems usually occur when Boolean objects are used in Boolean expressions. For example:
var oFalseObject = new Boolean(false); var bResult = oFalseObject && true; // Outputs true
In this code snippet, a Boolean object is created with the false value. Then this value is ANDed with the primitive value true. The result of ANDing false and true in Boolean operations is false. However, in this line of code, oFalseObject is being calculated, not its value false.
As discussed earlier, in Boolean expressions, all objects are automatically converted to true, so the value of oFalseObject is true. Then true is ANDed with true, resulting in true.
Note:Although you should be aware of the availability of the Boolean object, it is still better to use Boolean primitive values to avoid the issues mentioned in this section.
See
For more information about the Boolean object, please visit JavaScript Boolean Object Reference Manual.
Number object
As you might expect, the Number object is a reference type of the Number primitive type. To create a Number object, use the following code:
var oNumberObject = new Number(68);
You should have recognized the Number object mentioned in the previous section of this chapter when discussing special values (such as Number.MAX_VALUE). All special values are static properties of the Number object.
To obtain the Number primitive value of a numeric object, you simply need to use the valueOf() method:
var iNumber = oNumberObject.valueOf();
Of course, the Number class also has a toString() method, which has been discussed in detail in the section on type conversion.
In addition to the standard methods inherited from the Object object, the Number object also has several dedicated methods for handling numbers.
toFixed() method
The toFixed() method returns the string representation of a number with a specified number of decimal places. For example:
var oNumberObject = new Number(68); alert(oNumberObject.toFixed(2)); // Output: "68.00"
In this case, the parameter of the toFixed() method is 2, indicating that two decimal places should be displayed. This method returns "68.00", with empty string positions filled by 0. This method is very useful for applications dealing with currencies. The toFixed() method can represent numbers with 0 to 20 decimal places, and values outside this range will cause an error.
toExponential() method
Another method related to formatting numbers is toExponential(), which returns the string representation of a number in scientific notation.
Similar to the toFixed() method, the toExponential() method also has a parameter that specifies the number of decimal places to be output. For example:
var oNumberObject = new Number(68); alert(oNumberObject.toExponential(1)); // Output: "6.8e+1"
The result of this code is "6.8e+1", which has been explained before, representing 6.8x101The problem is, what if you don't know which form (predefined or exponential) to use to represent the number? You can use the toPrecision() method.
toPrecision() method
The toPrecision() method returns the predefined or exponential form of a number based on the most significant form. It has one parameter, which is the total number of digits used to represent the number (excluding the exponent). For example,
var oNumberObject = new Number(68); alert(oNumberObject.toPrecision(1)); // Output: "7e+1"
The task of this code is to represent the number 68 with one digit, resulting in "7e+1", which can also be expressed as 70. Indeed, the toPrecision() method rounds numbers.
var oNumberObject = new Number(68); alert(oNumberObject.toPrecision(2)); // Output: "68"
Of course, the output is "68", because that is the exact representation of the number. But what if the specified number of digits is more than needed?
var oNumberObject = new Number(68); alert(oNumberObject.toPrecision(3)); //Output "68.0"
In this case, toPrecision(3) is equivalent to toFixed(1), and the output is "68.0".
The toFixed(), toExponential(), and toPrecision() methods all perform rounding operations to represent a number correctly with the correct number of decimal places.
Tip:Similar to the Boolean object, the Number object is also very important, but it should be used less to avoid potential problems. As much as possible, use the primitive representation of numbers.
See
For more information about the Number object, please visit JavaScript Number Object Reference Manual.
String object
The String object is the object representation of the String primitive type, which is created in the following way:
var oStringObject = new String("hello world");
Both the valueOf() and toString() methods of the String object return the original value of the String type:
alert(oStringObject.valueOf() == oStringObject.toString()); //Output "true"
If this code is run, the output is "true", indicating that these values are indeed equal.
Note:The String object is one of the more complex reference types in ECMAScript. Similarly, the focus of this section is only on the basic functions of the String class. For more advanced features, please read the relevant sections of this tutorial or refer to JavaScript String Object Reference Manual.
length property
The String object has a property called length, which is the number of characters in the string:
var oStringObject = new String("hello world"); alert(oStringObject.length); //Output "11"
This example outputs "11", which is the number of characters in "hello world". Note that even if the string contains double-byte characters (relative to ASCII characters, which only occupy one byte), each character is counted as one character.
charAt() and charCodeAt() methods
The String object also has a large number of methods.
Firstly, both the charAt() and charCodeAt() methods access individual characters within a string. Both methods have a parameter, which is the position of the character to be operated on.
The charAt() method returns a string containing the character at the specified position:
var oStringObject = new String("hello world"); alert(oStringObject.charAt(1)); //Output "e"
In the string "hello world", the character at position 1 is "e". As mentioned in the section "ECMAScript primitive types", the position of the first character is 0, the position of the second character is 1, and so on. Therefore, calling charAt(1) returns "e".
If you want to get the character code instead of the character itself, you can call the charCodeAt() method:
var oStringObject = new String("hello world"); alert(oStringObject.charCodeAt(1)); //Output: "101"
This example outputs "101", which is the character code of the lowercase letter "e".
concat() method
Next is the concat() method, which is used to concatenate one or more strings to the original value of the String object. This method returns the original String value, leaving the original String object unchanged:
var oStringObject = new String("hello "); var sResult = oStringObject.concat("world"); alert(sResult); //Output: "hello world" alert(oStringObject); //Output: "hello "
In this piece of code, the return value of the concat() method is "hello world", but the String object still stores "hello ". For this reason, it is more common to concatenate strings using the plus sign (+), because this form logically indicates the true behavior:
var oStringObject = new String("hello "); var sResult = oStringObject + "world"; alert(sResult); //Output: "hello world" alert(oStringObject); //Output: "hello "
indexOf() and lastIndexOf() methods
So far, we have discussed methods for concatenating strings and accessing individual characters within a string. However, if you are unsure whether a character actually exists in a string, what method should you call? In this case, you can call the indexOf() and lastIndexOf() methods.
Both indexOf() and lastIndexOf() methods return the position of the specified substring within another string. If the substring is not found, it returns -1.
The difference between these two methods is that the indexOf() method searches for the substring from the beginning of the string (position 0), while the lastIndexOf() method starts searching from the end of the string. For example:
var oStringObject = new String("hello world!"); alert(oStringObject.indexOf("o")); Output: "4" alert(oStringObject.lastIndexOf("o")); Output: "7"
In this case, the first "o" string appears at position 4, which is the "o" in "hello"; the last "o" appears at position 7, which is the "o" in "world". If there is only one "o" string in the string, then the positions returned by indexOf() and lastIndexOf() methods are the same.
localeCompare() method
The next method is localeCompare(), which sorts strings. This method has one parameter - the string to be compared, and it returns one of the following three values:
- If the String object is alphabetically before the string in the parameter, it returns a negative number.
- If the String object is equal to the string in the parameter, it returns 0
- If the String object is alphabetically after the string in the parameter, it returns a positive number.
Note:If the return value is negative, the most common is -1, but the actual return value is determined by the implementation. If the return value is positive, the same is true, the most common is 1, but the actual return value is determined by the implementation.
Here is an example:
var oStringObject = new String("yellow"); alert(oStringObject.localeCompare("brick")); Output: "1" alert(oStringObject.localeCompare("yellow")); Output: "0" alert(oStringObject.localeCompare("zoo")); Output: "-1"
In this code snippet, the string "yellow" is compared with 3 values, namely "brick", "yellow", and "zoo". Since they are arranged in alphabetical order, "yellow" comes after "brick", so localeCompare() returns 1; "yellow" is equal to "yellow", so localeCompare() returns 0; and "zoo" comes after "yellow", so localeCompare() returns -1. To reiterate, since the returned value is determined by the implementation, it is best to call the localeCompare() method in the following way:
var oStringObject1 = new String("yellow"); var oStringObject2 = new String("brick"); var iResult = oStringObject1.localeCompare(oStringObject2); if(iResult < 0) { alert(oStringObject1 + " comes before " + oStringObject2); } else if (iResult > 0) { alert(oStringObject1 + " comes after " + oStringObject2); } else { alert("The two strings are equal"); }
With this structure, it can be ensured that this code runs correctly in all implementations.
The unique feature of the localeCompare() method is that the implementation location (locale, which refers to both country/region and language) precisely specifies how this method operates. In the United States, English is the standard language of the ECMAScript implementation, and localeCompare() is case-sensitive, with uppercase letters following lowercase letters in alphabetical order. However, this may not be the case in other regions.
slice() and substring()
ECMAScript provides two methods to create string values from substrings, namely slice() and substring(). Both methods return substrings of the string to be processed and accept one or two parameters. The first parameter is the starting position of the substring to be obtained, and the second parameter (if used) is the position before which the substring is to be obtained (that is, the character at the termination position is not included in the returned value). If the second parameter is omitted, the termination position is set to the length of the string by default.
Like the concat() method, the slice() and substring() methods do not change the value of the String object itself. They only return the original String value, keeping the String object unchanged.
var oStringObject = new String("hello world"); alert(oStringObject.slice("3")); // Output: "lo world" alert(oStringObject.substring("3")); // Output: "lo world" alert(oStringObject.slice("3", "7")); // Output: "lo w" alert(oStringObject.substring("3", "7")); // Output: "lo w"
In this example, the usage of slice() and substring() is the same, and the returned values are also the same. When only the parameter 3 is used, both methods return "lo world", because the second "l" in "hello" is at position 3. When there are two parameters "3" and "7", both methods return the value "lo w" (the letter "o" in "world" is at position 7, so it is not included in the result).
Why are there two methods with completely identical functions? In fact, these two methods are not completely identical; they only differ slightly in how they handle parameters when they are negative.
For negative parameters, the slice() method adds the parameter to the length of the string, while the substring() method treats it as 0 (which means it ignores it). For example:
var oStringObject = new String("hello world"); alert(oStringObject.slice("-3")); // Output: "rld" alert(oStringObject.substring("-3")); // Output: "hello world" alert(oStringObject.slice("3, -4")); // Output: "lo w" alert(oStringObject.substring("3, -4")); // Output: "hel"
This shows the main difference between the slice() and substring() methods.
When only the parameter -3 is used, slice() returns "rld", while substring() returns "hello world". This is because for the string "hello world", slice("-3") is converted to slice("8"), and substring("-3") is converted to substring("0").
Similarly, there is also a significant difference when using parameters 3 and -4. slice() will be converted to slice(3, 7), as in the previous example, returning "lo w". However, the substring() method interprets the two parameters as substring(3, 0), which is actually substring(0, 3) because substring() always takes the smaller number as the starting position and the larger number as the ending position. Therefore, substring("3, -4") returns "hel". The last line of code in this example is used to illustrate how to use these methods.
toLowerCase(), toLocaleLowerCase(), toUpperCase(), and toLocaleUpperCase()
The last set of methods to discuss involve case conversion. There are 4 methods used to perform case conversion, namely
- toLowerCase()
- toLocaleLowerCase()
- toUpperCase()
- toLocaleUpperCase()
As their names suggest, the first two methods are used to convert strings to all lowercase, and the latter two methods are used to convert strings to all uppercase.
The toLowerCase() and toUpperCase() methods are primitive and are implemented as prototypes of the same methods in java.lang.String.
The toLocaleLowerCase() and toLocaleUpperCase() methods are implemented based on a specific locale (as with the localeCompare() method). In many locales, the locale-specific methods are exactly the same as the general methods. However, several languages apply specific rules for Unicode case conversion (such as Turkish), so it is necessary to use the locale-specific methods to perform the correct conversion.
var oStringObject = new String("Hello World"); alert(oStringObject.toLocaleUpperCase()); //Output "HELLO WORLD" alert(oStringObject.toUpperCase()); //Output "HELLO WORLD" alert(oStringObject.toLocaleLowerCase()); //Output "hello world" alert(oStringObject.toLowerCase()); // Output 'hello world'
In this code, both toUpperCase() and toLocaleUpperCase() output 'HELLO WORLD', and both toLowerCase() and toLocaleLowerCase() output 'hello world'. Generally speaking, it is safer to use region-specific methods if you are not sure about the encoding in which a language is running.
Tip:Remember, all properties and methods of String objects can be applied to String primitive values because they are pseudo-objects.
Instanceof Operator
When using the typeof operator, a problem occurs when using reference types to store values, as it returns 'object' regardless of the type of object being referenced. ECMAScript introduced another Java operator instanceof to solve this problem.
The instanceof operator is similar to the typeof operator, used to identify the type of the object being processed. Unlike the typeof method, the instanceof method requires the developer to explicitly confirm that the object is of a specific type. For example:
var oStringObject = new String("hello world"); alert(oStringObject instanceof String); // Output 'true'
This code asks whether 'variable oStringObject is an instance of String object?' oStringObject is indeed an instance of String object, so the result is 'true'. Although it is not as flexible as the typeof method, the instanceof method is still very useful when typeof method returns 'object'.
- Previous Page ECMAScript Type Conversion
- Next Page Unary Operators