JavaScript 创建对象教程展示了如何在 JavaScript 中创建对象。可以使用对象文字、函数构造函数或类定义来创建对象。对象通常是使用创建构建器和工厂设计模式创建的。
在本文中,我们使用 Node.js 来执行示例。
对象字面量
在对象字面量表示法中,我们将用逗号分隔的对象属性放在大括号{} 内。
属性名称和值用冒号分隔。
const person = {
firstName: 'John',
lastName: 'Doe',
email: 'jdoe@example.com',
info: function() {
return `${this.firstName} ${this.lastName}, ${this.email}`
}
};
console.log(person.info());
该示例使用文字表示法创建了一个对象。
$ node object_literal.js John Doe, jdoe@example.com
对象构造函数
可以使用new Object 构造函数创建对象。然后使用点运算符动态添加属性。
let person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.email = 'jdoe@example.com';
person.info = function(){
return `${this.firstName} ${this.lastName}, ${this.email}`;
};
console.log(person.info());
该示例使用 Object 构造函数创建一个对象。
函数构造函数
函数构造函数是使用function 关键字创建的。它将值作为参数。使用this关键字设置属性。方法是使用this 和function 关键字创建的。使用 new 关键字创建新对象。
function Person(firstName, lastName, email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.info = function() {
return `${this.firstName} ${this.lastName}, ${this.email}`;
}
}
let person = new Person('John', 'Doe', 'jdoe@example.com');
console.log(person.info());
该示例使用函数构造函数创建了一个对象。
类定义
对象使用class 关键字定义并使用new 关键字生成。这是创建 C# 或 Java 等语言已知对象的经典方法。 JavaScript 使用constructor关键字来定义对象构造函数。属性使用this关键字设置。
class Person {
constructor(firstName, lastName, email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
info() {
return `${this.firstName} ${this.lastName}, ${this.email}`;
}
}
let person = new Person('John', 'Doe', 'jdoe@example.com');
console.log(person.info());
该示例使用类定义创建一个对象。
建造者模式
建造者模式是一种用于创建对象的创建型设计模式。它通过提供循序渐进的方法使用简单对象构建复杂对象。构建器模式使用流畅的 API 来创建对象。
let Person = function (firstName, lastName, email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
let PersonBuilder = function () {
let firstName;
let lastName;
let email;
return {
setFirstName: function (firstName) {
this.firstName = firstName;
return this;
},
setLastName: function (lastName) {
this.lastName = lastName;
return this;
},
setEmail: function (email) {
this.email = email;
return this;
},
info: function () {
return `${this.firstName} ${this.lastName}, ${this.email}`;
},
build: function () {
return new Person(firstName, lastName, email);
}
};
};
var person = new PersonBuilder().setFirstName('John').setLastName('Doe')
.setEmail('jdoe@example.com');
console.log(person.info());
该示例使用构建器设计模式创建对象。
工厂模式
使用工厂模式,我们可以在不向客户端公开创建逻辑的情况下创建对象。
const personFactory = (firstName, lastName, email) => {
return {
firstName: firstName,
lastName: lastName,
email: email,
info() {
return `${this.firstName} ${this.lastName}, ${this.email}`;
}
};
};
let person = personFactory('John', 'Doe', 'jdoe@example.com');
console.log(person.info());
该示例使用工厂模式创建了一个对象。
在本文中,我们使用不同的语法创建了 JavaScript 对象。我们还介绍了两种创建型设计模式,即构建器模式和工厂模式。
列出所有 JavaScript 教程。
