js创建对象
时间: 2023-07-23 08:04:20 浏览: 41
在 JavaScript 中,对象可以通过多种方式创建。
1. 对象字面量
使用大括号({})创建一个对象字面量,然后在其中定义属性和方法。
```javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
```
2. 构造函数
使用构造函数创建对象,首先需要定义一个构造函数,然后使用 `new` 关键字创建对象。
```javascript
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}
let person = new Person("John", "Doe", 30);
```
3. Object.create()
使用 Object.create() 方法创建一个新对象,新对象的原型是传入的参数对象。
```javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
let newPerson = Object.create(person);
```
4. Class
使用 ES6 中引入的 Class 关键字创建对象。
```javascript
class Person {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
fullName() {
return this.firstName + " " + this.lastName;
}
}
let person = new Person("John", "Doe", 30);
```