ZetCode

在 JavaScript 中创建对象

最后修改于 2023 年 10 月 18 日

在本文中,我们将展示如何在 JavaScript 中创建对象。对象可以使用对象字面量、函数构造函数或类定义来创建。对象通常使用创建型构建器和工厂设计模式来创建。

在本文中,我们使用 Node.js 来执行我们的示例。

对象字面量

在对象字面量表示法中,我们将对象的属性用逗号分隔,放在花括号 {} 中。

属性名称和值用冒号分隔。

object_literal.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 构造函数创建。然后使用点运算符动态添加属性。

object_constructor.js
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 关键字设置。方法使用 thisfunction 关键字创建。新对象使用 new 关键字创建。

function_constructor.js
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_definition.js
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 创建对象。

builder_pattern.js
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());

该示例使用构建器设计模式创建一个对象。

工厂模式

使用工厂模式,我们创建对象,而无需将创建逻辑暴露给客户端。

factory_pattern.js
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 对象。我们还介绍了两种创建型设计模式,即构建器模式和工厂模式。

来源

使用对象

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我撰写了超过 1,400 篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

查看 所有 JavaScript 教程。