Home >Web Front-end >JS Tutorial >how to create object in javascript

how to create object in javascript

下次还敢
下次还敢Original
2024-05-08 22:24:20328browse

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 object in javascript

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:

  • Object literal syntax: This is The fastest and easiest way to create objects.
<code class="js">const person = {
  name: "John Doe",
  age: 30,
  occupation: "Software Engineer",
};</code>
  • Constructor: You can create an object using a constructor, which is responsible for initializing the object properties.
<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>
  • Object.create(): This method creates a new object that inherits properties and methods from the specified prototype object.
<code class="js">const person = Object.create({
  name: "John Doe",
  age: 30,
  occupation: "Software Engineer",
});</code>
  • Class syntax (ES6): Classes provide a more modern way of creating objects.
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn