SoFunction
Updated on 2025-03-03

JavaScript learning notes to create objects

JavaScript has built-in objects such as Date, Array, String, etc. It has powerful functions and is easy to use, and is loved by everyone. However, when dealing with some complex logic, the built-in objects are powerless and often require developers to customize the objects.

From a JavaScript definition, an object is a collection of unordered properties, whose properties can contain basic values, objects, or functions. That is to say, an object is a set of attributes without a specific order. Each attribute will be mapped to a value, which is a set of key-value pairs, and the value can be data or objects.

Objects are the basic data types of JavaScript. In JavaScript, values ​​except strings, numbers, true, false, null and undefined are all objects. Therefore, it is very difficult to learn JavaScript without understanding the object learning. Start learning about the subject from today.

Overview

In JavaScript, objects are a basic data type, and in data structures, a hash table, which can be regarded as an unordered set of attributes. Everything except the original value is an object. These values ​​can be accessed by attribute names, which can be any string including null characters. To put it simply, an object is a collection of a series of attributes, and an attribute contains a name (key) and a value (value).

Understand what JavaScript objects are, you can think of this. In JavaScript, an object is a special body with attributes. Take a girl you see. This girl is a target and she has her own attributes. For example, the girl's height, age, name, etc. Similarly, in JavaScript, properties can also be used to define its features for an object.

Create an object

Since you want to learn objects, you have to have an object first. This is the question. How to create objects in JavaScript? Next, let’s take a look at how to create objects in JavaScript.

Many JavaScript books are mainly about how to introduce object creation methods:

Create an object using object literals (key-value)

Create an object using new

Create an object using ()

Create an object using functions

Create an object using a prototype

Create an object using object literal

Object literals are the easiest form of creating objects, with the purpose of simplifying the process of creating objects with a large number of attributes. An object literal is composed of several attribute names and attribute values. Key and value are separated by colon (:) and each pair of key/value is separated by comma (,), and the entire mapping table is enclosed in curly braces ({}).

The syntax for creating an object through object literals is as follows:

var obj = {
property_1: value_1, // property_# Probably an identifier...2: value_2, // Or a number// ...,
"property n": value_n // Or a string};

Here obj is the name of the created object, each property_i is an identifier (can be a name, number, or string literal), and each value_i is a value of its, and this value is assigned to property_i. Let’s take a look at a specific example:

var girl = {
'name': 'Xinxin',
'age' : 18,
'height': 175,
'weight': 45
}

This example creates an object named girl, which has four attributes name, age, height, and weight. These four attributes correspond to a property value.

When creating an object using an object literal, if you leave its curly braces ({}), you can define an object that contains only the default properties and methods. like:

var obj = {}

When using an object created in this way, you can create object properties for object obj through point (.), that is, and assign the object attribute value to the object. In addition, object properties can be created for object obj through square brackets ([]), that is, obj['key'], and attributes the object's property values. As in the following example:

var girl = {};
 = 'Xinxin';
 = 18;
girl['height'] = 175;
girl['weight'] = 45;

When printing a girl object in Chrome, the output result is as follows:

(girl);
//Object {name: "Xinxin", age: 18, height: 175, weight: 45}

Create an object using new

You can also create objects using the new operator followed by the Object constructor (about the constructor, let's talk about it later):

var obj = new Object(); // Same as obj = {}

Although obj is an empty object in the initial state, it is convenient to dynamically add and use members in JavaScript, so we can constantly add member variables and methods. like:

var girl = new Object();
girl['name'] = 'Xinxin';
girl['age'] = 18;
girl['height'] = 175;
girl['weight'] = 45;

Create an object using ()

Objects can also be created using the () method. This method is very useful because it allows you to select its prototype object for the created object without defining a constructor.

() method creates an object with a specified prototype and several specified attributes.

(proto, [ propertiesObject ])

The () method creates an object that accepts two parameters, the first parameter is the prototype object proto of this object; the second is an optional parameter to further describe the properties of the object. This method is very simple to use:

var obj1 = ({
x: 1,
y: 2
}); //Object obj1 inherits attributes x and yvar obj2 = (null); //Objectobj2No prototype

If the proto parameter is not null or an object value, a TypeError exception is thrown.
For more examples about the() method, click here to learn about it.

Create an object using functions

In actual use, although literal creation objects are useful, they cannot meet all our needs. We hope to create a class like other background languages, and then declare an instance of the class can be used multiple times without having to recreate it every time.

Because JavaScript does not have classes, it usually uses functions to define a class format similar to that in other languages, such as:

function Person() {
 = "mary"; // Add a member variable name to this class and assign a default value to this member variable = 5;
 = function () {
( + " : " + );
};
}

After defining the class, we can create and use objects like the following:

var person1 = new Person();
 = 'Tom';
 = 20;
(); // Tom : 20
var person2 = new Person();
 = 'W3cplus';
 = 5;
(); // W3cplus : 5

The Person() function is not used to be called, it is used to be used to new.

Create an object through a prototype

Compared with the previous methods, this method is the most complex and advanced method. Here also involves some knowledge about encapsulation (there are some subsequent learnings and then record them). Here is a simple look at how to create objects through prototypes.

First, just like a function method creates an object, first define a function:

function Person() {
 = "W3cplus";
 = 5;
 = function () {
("A front-end website...");
};
}

Then, externally, members can be expanded:

//Add member method = function () {
("hello");
};
//You can also add member attributes, = 100;

On the one hand, the prototype can expand the functions of the original class (especially adding useful methods), or write like below:

function Person() { }
 = "W3cplus";
 = 5;
 = function () {
("A front-end website...");
};
 = function () {
("hello");
};
 = 100;

Attribute access

There are generally two methods for object attribute access. The first is to use point (.) notation, which is also the most commonly used method and is also a common syntax in many object-oriented languages. The second method can also use brackets ([]) notation to access the object's properties. When using bracket syntax, the attributes to be accessed should be placed in brackets as strings. as follows:

person['name'];
;

Functionally speaking, there is no difference between accessing object properties of the above two methods. But there are two main advantages of bracket syntax:

Probably accessing properties through variables, as follows:

var propertyName = 'name';
person[propertyName];

Another advantage is that if the property name contains characters that will cause syntax errors or the property name uses keywords or reserved words, you can use brackets to access the property, as follows:

person['first name'];

In general, unless it is necessary to access object properties, it is recommended to use the point (.) method to access object properties.

Summarize

Objects are the basic data types of JavaScript. If you want to learn JavaScript-related knowledge better, it is necessary to first understand the object. This article mainly introduces several methods of creating objects. The simpler one is created through the literal ({}) and new Object() methods, but the objects created by these two methods are poorly reusable; when creating an object using () you do not need to define a constructor to allow you to select its prototype object in the object. In addition to these methods, you can also use functions and prototypes to create objects. These two methods are relatively reusable, but they are more complicated to use.

The editor will introduce you to the knowledge about creating objects about JavaScript learning notes, hoping it will be helpful to you!