Home > Article > Web Front-end > how to create object in javascript
There are four ways to create objects in JavaScript: object literal syntax, constructor, Object.create() method, and class syntax (ES6). Object properties can be accessed and modified through dot operator or square bracket notation, while the delete operator can be used to delete properties.
How to create objects in JavaScript
Introduction
Objects are objects in JavaScript The basic structure for storing data. They allow data to be organized into key-value pairs for easy access and manipulation.
Creating Objects
There are several ways to create objects in JavaScript:
<code class="js">const person = { name: "John Doe", age: 30, occupation: "Software Engineer", };</code>
<code class="js">function Person(name, age, occupation) { this.name = name; this.age = age; this.occupation = occupation; } const person = new Person("John Doe", 30, "Software Engineer");</code>
<code class="js">const person = Object.create({ name: "John Doe", age: 30, occupation: "Software Engineer", });</code>
<code class="js">class Person { constructor(name, age, occupation) { this.name = name; this.age = age; this.occupation = occupation; } } const person = new Person("John Doe", 30, "Software Engineer");</code>
Access object properties
You can use the dot operator (.
) or square bracket notation ([]
)Access object properties:
<code class="js">console.log(person.name); // John Doe console.log(person["age"]); // 30</code>
Modify object properties
You can modify object properties using the same method as accessing properties:
<code class="js">person.name = "Jane Doe"; person["age"] = 31;</code>
Delete object properties
You can use the delete
operator to delete object attributes:
<code class="js">delete person.occupation;</code>
The above is the detailed content of how to create object in javascript. For more information, please follow other related articles on the PHP Chinese website!