This is the 13th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Hello everyone, I am the prosperity of the other shore 🌸, a front-end 👨🏻💻 that firmly believes that hard work can change destiny. If I have the honor to write an article that can get your favor, I am very lucky ~

This series of articles was first published in nuggets

Writing in the front

In this article we’ll look at objects in JavaScript. What can I learn from this article? The diagram below:

Concept of objects

The concept of an object contains what is an object, the properties of an object, the methods of an object, and so on. Now we will learn in turn.

What is an object

An Object is a complex data type in JavaScript. Simply put, an Object is a collection of properties or methods.

We can understand objects through objects in real life. For example, we can think of a cup as an object. Then the cup has information such as color, size and weight, which we can understand as properties of the cup. While we use a cup to drink water, the action of drinking water can be understood as the method of the cup.

In this sense, the properties of an object are a set of information describing the object, and the methods of an object are a set of information describing what the object can do.

JavaScript is designed in a very simple object-based way, that is, in fact, all the variables and functions we’ve talked about before are properties or methods of objects.

The following example code shows objects in JavaScript

var obj = {
  name: 'cup'.drink: function(){
    console.log('The cup can be used for drinking.')}}Copy the code

The sample code above creates an object called obj, which has a name attribute and a drink method.

Note: The sample code above is for demonstration purposes only.

Classification of objects

Objects in JavaScript can be classified into the following three types according to their functions and application scenarios:

  • Built-in objects: Also known as native objects, are predefined objects in JavaScript. Defined by the ECMA-262 standard specification, implemented and provided by the JavaScript interpreter/engine

  • Host object: is provided by the JavaScript runtime environment. For example, the browser environment provides a set of objects such as DOM and BOM.

  • Custom objects: Objects created by developers according to their needs.

Object

Object in JavaScript is a predefined function and a constructor.

Object is the parent of all reference types in the JavaScript language. All reference types can directly use the properties and methods provided by Object.

In simple terms, we can create objects using either the Object() function or the Object() constructor. Whether you use Object() or new Object() is equivalent.

The method of the Object

Of course, since Object is a constructor in the JavaScript language, Object itself provides a set of methods. This series of methods can be divided into two categories, as follows:

  • Proprietary methods: Methods of the constructor itself. A method added by reference to an object. Other objects may not have this method; If there are, they are independent of each other. For example, the keys() method is used to get the names of all the properties in the current object that have their own enumerable properties.

  • Prototype method: The method defined by the prototype. Used to share properties and methods. Methods inherited from a stereotype object. Once a method in the stereotype object changes, all methods on objects inherited from that stereotype change. For example, the hasOwnProperty() method is used to determine whether the current object contains a specified property.

Create an object

In the process of development, in addition to using the objects provided by JavaScript and the host environment, we can also create objects according to our own needs. There are three ways to create objects in JavaScript, as shown below:

  • Literal methods create objects

  • The constructor creates an object

  • The object.create () method creates an Object

Literal methods create objects

Creating objects using literals is one of the easiest ways to create objects in JavaScript. The syntax structure is as follows:

varObj = {attribute name1: attribute values1, the property name2: attribute values2. The method name1: function(The list of parameters) {method body1}, the method name2: function(The list of parameters) {method body2},... }Copy the code

The object initializer uses curly braces ({}) to create objects. It is important to note that the curly braces here do not represent blocks of statements, but objects.

We can also create an anonymous object with the following syntax structure:

varObj = {attribute name1: attribute values1, the property name2: attribute values2. The method name1: function(The list of parameters) {method body1}, the method name2: function(The list of parameters) {method body2},... }Copy the code

Anonymous objects cannot be referenced elsewhere.

The following is an example of code for creating objects using literals:

// obj specifies the name of the object
var obj = {
    name: 'cup'.// represents attributes
    drink: function () { // Indicate the method
        console.log('The cup can be used for drinking.')}}console.log(obj) // { name: '杯子', drink: [Function: drink] }
Copy the code

Create objects using constructors

There are two ways to use a constructor to create an object. One is to use one of JavaScript’s predefined constructors, such as Array(). In JavaScript, arrays are also objects. Another is to use custom constructors to create objects.

We’ll learn about custom constructors in JavaScript Advanced Syntax.

To create an object instance using the constructor method:

// Create an array. In JavaScript, arrays are objects
var arr = new Array('1')
console.log(typeof arr) // object
Copy the code

Use the object.create () method to create an Object

The create() method provided by Object also creates an Object, and using this method to create an Object allows the Object to select its prototype Object instead of defining a constructor.

We’ll learn more about prototype objects in JavaScript Advanced Syntax.

The syntax for object.create () is as follows:

Object.create(prototype object [, free property])Copy the code

The example code for an Object created using the object.create () method is as follows:

// Define an object as a prototype
var bird = {
    name: 'the birds'.sayMe: function () {
        console.log('I am a bird'); }}// Use object.create() to create the object and use bird as the prototype object

var swallow = Object.create(bird)

console.log(swallow.name) / / the bird
Copy the code

Properties of an object

In JavaScript, an object can have multiple properties (in fact, almost all programming languages, an object can have multiple properties), and one property represents one piece of information about the object. Simply put, the properties of an object are the variables attached to the object.

The naming rules for attributes are the same as for variables, as long as it is noted that accessing a property of an undefined object does not result in an error; instead, undefined is returned. The example code is as follows:

var obj = {}

console.log(obj.name) // undefined
Copy the code

Access the properties of an object

When an object is created, it has one or more properties, and the data content stored in that property can be accessed through a property name of the object. There are two ways to do this, as shown below:

  • Through the dot symbol (.) Access the properties of an object

  • Access the properties of an object through square brackets ([])

The following example code shows two ways to access an object’s properties:

var person = {
    name: 'Prosperity on the other side'.hobby: 'coding'
}
// Use
console.log(person.name) // The other side is bustling

// Use [] to access
console.log(person['hobby']) // coding
Copy the code

The dot symbol is a common way to access the properties of an object, but the square bracket is a more general way to access the properties of an object. For example, when there are complex property names in an object, accessing them through dot symbols may be problematic, but accessing them through square brackets is not. As shown in the following example code:

var header = {
    'charset': 'UTF-8'.'Content-Type': 'text/html'
}

console.log(header["Content-Type"]) // text/html
// Console. log(header.content-type) // Error is reported
Copy the code

Add attributes to an object

In general, when an object is created, its required properties are defined together. But in development work, it is often necessary to continue to maintain new properties for an object. JavaScrip allows you to add properties to an existing object in two ways, as shown below:

  • Through the dot symbol (.) Adds a property to an object

  • Increments an object’s properties through square brackets ([])

The example code is as follows:

var person = {
    name: 'Prosperity on the other side'.hobby: 'coding'
}
// Use
person.name = 'Prosperity on the other side'
// Use [] to access [any string]
person['hobby'] = 'coding'

console.log(person.name) // The other side is bustling
console.log(person['hobby']) // coding

Copy the code

Deletes the properties of an object

With the delete operator, we can delete the properties of an object. The sample code is as follows

var obj = {
  name: 'MacBook'.price:9999
}
console.log(obj.name, '\t\t', obj.price) // MacBook 9999
// Delete its properties with
delete obj.name
// Delete its attributes when matching []
delete obj.price
console.log(obj.name, '\t\t', obj.price) // undefined undefined
Copy the code

Iterate over the properties of an object

Since an object can have one or more properties, it can also be divided into its own properties and prototype properties. Sometimes we need to get all the properties of an object, so we need to do it by traversal. As follows:

  • for… In loop: This method accesses all the enumerable properties of an object and its prototype chain in turn.

  • Object.keys(Object) method: This method returns an array containing the names of all of the Object’s own enumerable properties.

  • Object. GetOwnPropertyNames (Object) method, this method returns an array, the array contains all the properties of the Object name.

Enumerable and non-enumerable will be learned in JavaScript Advanced Syntax.

for… In statement

We learned about for when we studied arrays… In statement. This statement not only iterates over the array, but it also iterates over all the enumerable properties in the object.

In the case of traversing an object’s properties, for… The in statement is simple and effective. As shown in the following example code:

var person = {
    name: 'li lei'.age: 28.job: 'Shop assistant'.sex: 'male'
}
for (attr in person) {
    console.log(person[attr])
}
Copy the code

The above code prints every property in the object.

It is worth noting that since… Attr in the in statement is a variable that can only be obtained using square brackets, not dot notation.

Object. The keys () method

The object.keys () method is a method provided by an Object that takes an Object as an argument and returns the names of all the properties in that Object that have their own enumerable properties.

The example code is as follows:

var person = {
    name: 'li lei'.age: 28.job: 'Shop assistant'.sex: 'male'
}
// 1. Obtain the attribute name
var attrNames = Object.keys(person)
for (var i = 0; i < attrNames.length; i++) {
    var attrName = attrNames[i]
    // Get the value from the property name
    console.log(person[attrName])
}
Copy the code

Object. GetOwnPropertyNames () method

Object. GetOwnPropertyNames () method and the Object. The keys () method is similar, different is the method will return all property names, and the Object. The keys () method only returns its attributes can be enumerated.

The example code is as follows:

var person = {
    name: 'li lei'.age: 28.job: 'Shop assistant'.sex: 'male'
}

// 1. Obtain the attribute name
var attrNames = Object.getOwnPropertyNames(person)
for (var i = 0; i < attrNames.length; i++) {
    var attrName = attrNames[i]
    // Get the value from the property name
    console.log(person[attrName])
}
Copy the code

Object methods

In JavaScript, an object can have multiple methods, with one method describing the behavior of an object. Simply put, methods on an object are variables attached to that object

The methods of the object are added, deleted, modified and checked in the same way. The only difference is that the object is callable.

conclusion

Preview: We’ll look at reference types in JavaScript in the next article

Excellent articles

Scope in JavaScript

09-JavaScript functions (all basic, see if you can do it)

The basics of arrays in JavaScript may be something you don’t know

07- Learn to loop in JavaScript

06- This time I learned conditionals in JavaScript