JavaScript Object Types
The fourth chapter of JavaScript advanced programming has been learned. However, because Chapter 5 describes various object types, before learning chapter 5, it is advantageous to have a deeper understanding of objects. JavaScript Objects in Detail all aspects of object types are clearly written in this article. Based on the principle of not repeating the wheel, I am not planning to write another article here, what's more, my new handwritten article is definitely incomparable with others. Since many friends may not be very interested in English, I am going to translate the article here. However, I declare in advance that I have no translation experience and the translated articles may be poor. If the English version is better, you are advised to read the original text directly. After all, this is a new attempt. If you have any suggestions or comments, you can post them in the comments, but do not spray them without reason. For details about JavaScript Object Types, JavaScrtip has six data types: a complex data type (reference type), that is, the Object type, and five simple data types (original type ): number, String, Boolean, Undefined, and Null. The core type is the object type. At the same time, it should be noted that the simple types are immutable, and the object type is variable. What is an object? An object is an unordered list of simple data types (sometimes reference data types) and is stored as a series of name-value pairs (name-value pairs ). Each item in this list is called an attribute (a function is called a method ). The following is a simple object: var myFirstObject = {firstName: "Richard", favoriteAuthor: "Conrad"}; you can consider an object as a list, each item (attribute or method) in the list is stored as a name-value pair. In the above example, the object's attribute names are firstName and favortieAuthor. Correspondingly, the object's attribute values are Richard and Conrad. The attribute name can be a string or number. However, if you use a number as the attribute name, you must use square brackets (square brackets) to obtain the attribute value corresponding to this numeric attribute name. A more detailed explanation of square brackets will be provided later. The following is an example of square brackets: var ageGroup = {30: "Children", 100: "Very Old"}; console. log (ageGroup.30) // error // the correct method for accessing the 30 Attribute console. log (ageGroup ["30"]); // Children // it is best to avoid using numbers as attribute names as JavaScript programmers. You will often use object data types. It is generally used to store data or create custom methods or functions. A major difference between the reference data type and the original data type is that the reference type is stored by reference. It does not store values directly in variables like the original type. For example: // the original data type is stored by value var person = "Kobe"; var anotherPerson = person; // anotherPerson = the value of person = "Bryant "; // The value of person changes the console. log (anotherPerson); // Kobe console. log (person); // Bryan can note that even if we change the person value to "Bryant", anthoerPerson will not be affected at all, it still saves the value originally assigned to it by person. Compare the original-type value-based storage with the reference-type reference-based storage: var person = {name: "Kobe"}; var anotherPerson = person; person. name = "Bryant"; console. log (anotherPerson. name); // Bryant console. log (person. name); // in this example, we copy the person object to anthoerPerson, but because the person object stores references rather than true values. So when we set the person. when the name is changed to "Bryant", the anotherPerson variable also reflects this change because it does not copy and save all attributes in person, instead, the object reference is saved directly. Attributes of an object (Attributes) Note: Attribute is usually translated as an Attribute. However, to distinguish it from Propertie (also translated as an Attribute), the Attribute is translated as a feature, this is also consulted by others. It should be harmless. Each object attribute not only saves its own name-value pair, but also contains three features, these three features are set to true by default. Retriable Attribute: Specifies whether the object Attribute can be deleted or modified. Enumerable: Specifies whether the object property can be obtained in the for-in loop. Writable: Specifies whether this object attribute can be modified. There are some new features in EMACScript 5, which are not described in detail here. There are two common methods to create an object: The literal volume of an object, which is the most common and simplest method to create an object. You can directly create an object using the literal volume: // empty object var myBooks ={}; // The object var mango = {color: "yellow", shape: "round" that contains four attributes is created using the literal ", sweetness: 8, howSweetAmI: function () {console. log ("Hmm Good") ;}} object constructor the second common method is to use object constructor. Constructor is a special function that can be used to create new objects. You must use the new keyword to call constructor. Var mango = new Object (); mango. color = "yellow"; mango. shape = "round"; mango. sweetness = 8; mango. howSweetAmI = function () {console. log ("Hmm Good");} although some reserved words or keywords can be used, for example, for object attribute names, this is not a wise choice. Object Attributes can contain any data type, including Number, Arrays, and even other objects. The practice mode of object creation can meet the requirements of the above two methods for creating a simple object that is used only once for data storage. However, assume that a program is used to display the fruit and its details. Each fruit type in the program has the following object attributes: color, shape, sweetness, cost, and a showName function. It would be boring and inefficient to repeat the following code every time you create a new fruit object. Var mangoFruit = {color: "yellow", sweetness: 8, fruitName: "Mango", nativeToLand: ["South America", "Central America"], showName: function () {console. log ("This is" + this. fruitName) ;}, nativeTo: function () {this. nativeToLand. forEach (function (eachCountry) {console. log ("Grown in:" + eachCountry) ;}}} if you have 10 fruits, you have to add the same code 10 times. If you want to modify the nativeTo function, You have to modify it in 10 different places. Further imagine that if you are developing a large website, you have added attributes for all the objects above. However, you suddenly find that the method for creating an object is not ideal. What should you do if you want to modify the object. To solve these repetitive problems, software engineers have developed various models (solutions for repetitive issues and common tasks) to make development programs more efficient and rational. Below are two common modes for object creation: constructor mode function Fruit (theColor, theSweetness, theFruitName, theNativeToLand) {this. color = theColor; this. sweetness = theSweetness; this. fruitName = theFruitName; this. nativeToLand = theNativeToLand; this. showName = function () {console. log ("This is a" + this. fruitName);} this. nativeTo = function () {this. nativeToLand. forEach (function (eachCountry) {console. log ("Grown in:" + EachCountry) ;};}using this mode, you can easily create a variety of fruits. Like this: var mangoFruit = new Fruit ("Yellow", 8, "Mango", ["South America", "Central America", "West Africa"]); mangoFruit. showName (); // This is a Mango. mangoFruit. nativeTo (); // Grown in: South America // Grown in: Central America // Grown in: West Africa var pineappleFruit = new Fruit ("Brown", 5, "Pineapple", ["United States"]); pineappleFruit. showName (); // This is a Pineapple. if you want to change attributes or methods, you only need to repair them in one place. You can change it. This mode encapsulates the functions and features of all fruits through inheritance of a Fruit function. Note: The property that can be inherited must be defined on the prototype Object Property of the object. For example, someObject. prototype. firstName = "rich"; attributes of the object must be directly defined on the object. For example: // first, create an object var aMango = new Fruit (); // then, define the semantic spice method directly on the object // because we define the mangoSpice attribute directly on the object, it is aMango's own attribute, not an inherited attribute aMango. mangoSpice = "some value"; to access the attributes of an object, use object. property, such as console. log (aMango. mangoSpice); // "some value" to call an object method, use object. method (), such as: // first, add a method aMango. printStuff = function () {return "Printing";} // now, you can call the printStuff method aMango. printStuff (); prototype mode function Fruit (){} Fruit. prototype. color = "Yellow"; Fruit. prototype. sweetness = 7; Fruit. prototype. fruitName = "Generic Fruit"; Fruit. prototype. nativeToLand = "USA"; Fruit. prototype. showName = function () {console. log ("This is a" + this. fruitName);} Fruit. prototype. nativeTo = function () {console. log ("Grown in:" + this. nativeToLand);} The following is the method for calling the Fruit () constructor in prototype mode: var mangoFruit = new Fruit (); mangoFruit. showName (); // MangoFruit. nativeTo (); // This is a Generic Fruit // Grown in: USA extended reading if you need to learn more about the two modes, you can read the sixth chapter of JavaScript advanced programming. The advantages and disadvantages of these two methods are discussed in detail. The book also discusses other models except the two. The dot notation method and bracket notation method are the two main methods for accessing object attributes ). Note method // This is the method that we used to access attributes in the previous example. var book = {title: "Ways to Go", pages: 280, bookMark1: "Page 20"}; // access the title and pages attributes of the book object by using the vertex method: console. log (book. title); // Ways to Go console. log (book. pages); // 280 brackets // use square brackets to reveal the attributes of accessing the book object: console. log (book ["title"]); // Ways to Go console. log (book ["pages"]); // 280 // If the attribute name is stored in a variable, you can also do this: var bookTitle = "title"; console. log (book [bookTitle]); // Ways Go console. log (book ["bookMark" + 1]); // Page 20 when you access an attribute that does not exist in an object, an undefined attribute is obtained. Attributes and inherited attribute objects have their own attributes and inherited attributes. Its own attributes are directly defined on the Object, and the inherited attributes are inherited from the Prototype of the Object. To determine whether an object has a certain attribute (whether its own attribute or its inheritance attribute), you can use the in OPERATOR: // to create an object with the schoolName attribute var school = {schoolName: "MIT"}; // print out true because the object has the schoolName Attribute console. log ("schoolName" in school); // true // print out false, because neither schoolType attribute is defined nor schoolType Attribute console is inherited from the Prototype of the Object. log ("schoolType" in school); // false // print true because the toString method console is inherited from the Prototype of the Object. log ("toString" in school); // truehasOwnProperty to determine You can use the hasOwnPrototype method to determine whether an object has a specific attribute. This method is very useful, because we often need to enumerate all the attributes of an object rather than inherit the attributes. // Create an object with the schoolName attribute var school = {schoolName: "MIT"}; // print out true, because the schoname is the master of the school. log (school. hasOwnProperty ("schoolName"); // true // print out false, because toString is inherited from the Prototype of the Object and its own Attribute console of school. log (school. hasOwnProperty ("toString"); // false to access and enumerate the attributes of an object in order to access the attributes that can be enumerated in the object (itself or inherited ), you can use a for-in loop or a normal loop. // Create a school object with three attributes: schoolName, schoolAccredited, and schoolLocation. var school = {schoolName: "MIT", schoolAccredited: true, schoolLocation: "Massachusetts"}; // use the for-in loop to obtain the attributes of the object for (var eachItem in school) {console. log (eachItem); // Prints schoolName, schoolAccredited, schoolLocation}. attributes inherited from the Prototype of the Object cannot be enumerated, therefore, these attributes are not accessed in the for-in loop. However, if they are eXtensible inheritance attributes, they can also be accessed from the for-in loop. For example: // use for-in to cyclically access the attribute for (var eachItem in school) {console. log (eachItem); // Prints schoolName, schoolAccredited, schoolLocation} // NOTE: The following description is the original description/* side note: As Wilson (an astute reader) correctly pointed out in the comments below, the educationLevel property is not actually inherited by objects that use the HigherLearning constructor; instead, the educationLevel property is create D as a new property on each object that uses the HigherLearning constructor. the reason the property is not inherited is because we use of the "this" keyword to define the property. * // Create a new HigherLearning function that the school object will inherit from. function HigherLearning () {this. educationLevel = "University";} // Implement inheritance with the HigherLearning constructor var s Chool = new HigherLearning (); school. schoolName = "MIT"; school. schoolAccredited = true; school. schoolLocation = "mascript usetts"; // Use of the for/in loop to access the properties in the school object for (var eachItem in school) {console. log (eachItem); // Prints educationLevel, schoolName, schoolAccredited, and schoolLocation} You can use the delete operator to delete attributes in an object. We cannot delete the inherited attributes, nor delete the Object Attributes With the resumable attribute set to false. To delete an inherited attribute, you must delete it from the Prototype object (that is, the place where these attributes are defined ). In addition, we cannot delete attributes in global objects. When the deletion is successful, the delete operator returns true. Unexpectedly, the delete operator returns true if the attribute to be deleted does not exist or cannot be deleted (that is, its own attribute or the retriable attribute is set to false. The following is an example: var christmasList = {mike: "Book", jason: "sweater"} delete christmasList. mike; // deletes the mike property for (var people in christmasList) {console. log (people);} // Prints only jason // The mike property was deleted delete christmasList. toString; // returns true, but because toString is an inherited attribute, it will not be deleted. // because toString is not deleted, it can still be used normally here. toString (); // "[object Object]" // If an attribute is an object instance's own attribute, you can To delete it. // For example, you can delete the educationLevel attribute from the school object defined in the previous example. // because educationLevel is defined in that instance: the "this" keyword is used when educationLevel is defined in the HigherLearning function. // We have not defined the educationLevel attribute in the prototype object of the HigherLearning function. Console. log (school. hasOwnProperty ("educationLevel"); // true // educationLevel is an attribute of a school object. Therefore, you can delete the school object. educationLevel; // true // The educationLevel attribute has been deleted from the school instance. log (school. educationLevel); // undefined // but the educationLevel attribute still exists in the HigherLearning function var newSchool = new HigherLearning (); console. log (newSchool. educationLevel); // University // if we use the prototype function in HigherLearning Defines an attribute, such as the educationLevel2 attribute: HigherLearning. prototype. educationLevel2 = "University 2"; // The educationLevel2 attribute is not the property of the HigherLearning instance. // The educationLevel2 attribute is not the console of the school instance. log (school. hasOwnProperty ("educationLevel2"); false console. log (school. educationLevel2); // University 2 // try to delete the inherited educationLevel2 attribute delete school. educationLevel2; // true (as mentioned earlier, this expression returns true) // The inherited educationLevel 2. The property is not deleted. log (school. educationLevel2); University 2 serialization and deserialization objects must be serialized (converted to a string) to pass objects in HTTP or convert objects into strings ). We can use JSON. stringify to serialize objects. Note that for versions earlier than ECMAScript 5, we need to use the json2 library to obtain the JSON. stringify function. In ECMAScript 5, this function has become a standard function. To deserialize an object (that is, convert a string to an object), you can use the JSON. parse function. Similarly, before version 5th, you must obtain this function from the json2 library. This standard function has been added to version 5th. Sample Code: var christmasList = {mike: "Book", jason: "sweater", chelsea: "iPad"} JSON. stringify (christmasList); // Prints this string: // "{" mike ":" Book "," jason ":" sweater "," chels ": "iPad"} "// To print a stringified object with formatting, add" null "and" 4 "as parameters: JSON. stringify (christmasList, null, 4); // "{//" mike ":" Book ", //" jason ":" sweater ", //" chels ": "iPad" //} "// JSON. parse Examples // The following is a JSON string, so we cannot access the properties with dot notation (like christmasListStr. mike) var christmasListStr = '{"mike": "Book", "jason": "sweater", "chels": "iPad "}'; // Let's convert it to an object var christmasListObj = JSON. parse (christmasListStr); // Now that it is an object, we use dot notation console. log (christmasListObj. mike); // Book