用 JavaScript 建立对象的方法有:对象字面量、new 关键字、Object.create() 方法、工厂函数和 Class。

如何用 JavaScript 建立一个对象?
JavaScript 中的对象是一个无序的属性集合,属性包含一个键和一个值。创建一个对象有很多种方法:
1. 对象字面量
这种方法是最简单直接的:
<code class="js">const person = {
name: "John Doe",
age: 30,
occupation: "Software Engineer"
};</code>2. new 关键字
可以使用 new 关键字创建一个对象:
<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>3. Object.create() 方法
此方法根据一个现有对象创建一个新对象,新对象的原型指向该现有对象:
<code class="js">const person = {
name: "John Doe",
age: 30,
occupation: "Software Engineer"
};
const newPerson = Object.create(person);
newPerson.name = "Jane Doe";</code>4. 工厂函数
工厂函数可以用来创建具有相同属性和方法的多个对象:
<code class="js">function createPerson(name, age, occupation) {
return {
name: name,
age: age,
occupation: occupation
};
}
const person = createPerson("John Doe", 30, "Software Engineer");</code>5. Class
ES6 中引入了 class,它是一种语法糖,可以更方便地创建和管理对象:
<code class="js">class Person {
constructor(name, age, occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
getName() {
return this.name;
}
}
const person = new Person("John Doe", 30, "Software Engineer");</code>










