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:
const person = { name: "John Doe", age: 30, occupation: "Software Engineer", };
function Person(name, age, occupation) { this.name = name; this.age = age; this.occupation = occupation; } const person = new Person("John Doe", 30, "Software Engineer");
const person = Object.create({ name: "John Doe", age: 30, occupation: "Software Engineer", });
class Person { constructor(name, age, occupation) { this.name = name; this.age = age; this.occupation = occupation; } } const person = new Person("John Doe", 30, "Software Engineer");
Access object properties
You can use the dot operator (.
) or square bracket notation ([]
)Access object properties:
console.log(person.name); // John Doe console.log(person["age"]); // 30
Modify object properties
You can modify object properties using the same method as accessing properties:
person.name = "Jane Doe"; person["age"] = 31;
Delete object properties
You can use the delete
operator to delete object attributes:
delete person.occupation;
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!