JavaScript 中创建对象的六种方法

2025-06-04

JavaScript 中创建对象的六种方法

对象是 JavaScript 中的基本数据类型之一。作为一名 JavaScript 开发者,你会发现自己经常使用它们。了解如何创建对象将会非常有用。在本教程中,你将学习如何在 JavaScript 中通过六种方式创建对象。

快速介绍

在 JavaScript 中,通常有多种方法可以完成同一件事。这包括创建新对象。到目前为止,至少有六种方法可以做到这一点。本教程将向您展示每一种方法。首先,您将学习如何使用对象字面量和new关键字创建新对象。

Object.create()接下来,你将学习如何使用原生方法创建对象Object.assign()。之后,你还将学习如何使用函数构造函数和 ES6 类来实现这一点。事不宜迟,让我们开始吧。

1. 对象字面量

{}使用对象字面量是 JavaScript 中创建对象的首选方法。它很可能也是最容易学习、记忆和使用的方法。这或许也是它成为 JavaScript 中创建对象最流行方法的原因。通过这种方式创建对象非常简单。只需用花括号 ( )包裹键值对即可。

这些键值对是您希望对象具有的键值对keysvalues对象的另一个key常用名称是“属性”。键(或属性)位于键值对的左侧,值位于右侧。两者之间用冒号 ( key: value) 隔开。

当你用花括号括起来时,你就得到了一个对象。如果你想创建一个空对象,只需使用花括号即可。之后,你可以将这个新对象赋值给某个变量。或者,你也可以直接使用它。

// Creating object with object literal.
const myObj = {
  name: 'Tom Jones',// One key-value pair.
  role: 'admin',
  isWorking: false,
  sayHi: function() {
    return `Hi, my name is ${this.name}.`
  }
}

// Log the object to console.
console.log(myObj)
// Output:
// {
//   name: 'Tom Jones',
//   role: 'admin',
//   sayHi: ƒ sayHi()
// }


// Creating an empty object with object literal.
const myEmptyObj = {}

// Log the object to console.
console.log(myEmptyObj)
// Output:
// {}
Enter fullscreen mode Exit fullscreen mode

第二点:“新”字

创建对象的第二种方法是使用new关键字Object() 构造函数。使用此构造函数时,它会返回一个值,即新对象。您可以将此对象赋值给一个变量,以便继续使用它。如果要添加新属性,可以执行以下两种操作。

第一种方法是创建一个空对象并将其赋值给一个变量。然后,你可以使用点符号或方括号向该对象添加属性。这种方法每次只能定义一个属性。因此,如果你想创建多个属性,则需要重复此操作几次。

第二种选择是将一个对象Object()作为参数传递给构造函数。这也会创建一个具有所需属性和值的对象。但是,如果要传递一个对象,使用Object()构造函数就显得多余了。这可能不是一个好的做法,绝对不推荐。

在这种情况下,你可以使用对象字面量的方式。我们在上一节中讨论过这一点。

// Creating object with object constructor.
const myObj = new Object()

// Add properties.
myObj.username = 'Skylar'
myObj.gender = 'female'
myObj.title = 'Fullstack dev'

// Add a method.
myObj.sayHi = function() {
  return `Hi, I am ${this.username}.`
}

// Log the object to console.
console.log(myObj)
// Output:
// {
//   username: 'Skylar',
//   gender: 'female',
//   title: 'Fullstack dev'
//   sayHi: ƒ ()
// }


// Passing an object - not a good idea
const myObj = new Object({
  username: 'Skylar',
  gender: 'female',
  title: 'Fullstack dev'
})

// Log the object to console.
console.log(myObj)
// Output:
// {
//   username: 'Skylar',
//   gender: 'female',
//   title: 'Fullstack dev'
// }
Enter fullscreen mode Exit fullscreen mode

No.3:Object.create()方法

当你想基于现有Object.create()方法创建新对象时,这种方法非常有用。此方法接受两个参数。第一个参数用于指定要复制的原始对象。这将是prototype。第二个参数用于指定要添加到新对象的属性和值。

当您使用此方式添加新属性时,请记住一件事。您是通过 [property descriptor] 指定新属性的值value,而不是直接指定。您还可以指定其他标志,例如writableenumerableconfigurable。您可以为每个要添加的属性执行此操作。

与构造函数类似Object(),此方法也会返回新对象。因此,请在使用时将其赋值给一个变量,以便后续操作。

// Create new object (using object literal).
const human = {
  species: 'human',
  isAlive: true
}

// Create new object "female" with Object.create()
// and use "human" as the prototype
// and add two new properties - "gender" and "pregnant".
const female = Object.create(human, {
  // Add "gender" property.
  gender: {
    value: 'female', // Value of "gender" property.
    writable: true,
    enumerable: true,
    configurable: true
  },
  // Add "pregnant" property.
  pregnant: {
    value: false, // Value of "pregnant" property.
    writable: true,
    enumerable: true,
    configurable: true
  }
})

// Log the "female" object.
console.log(female)
// Output:
// {
//   gender: 'female',
//   pregnant: false,
//   __proto__: {
//     species: 'human',
//     isAlive: true
//   }
// }

// Log the value of "gender" property.
console.log(female.gender)
// Output:
// 'female'

// Log the value of "species" property.
// This property is inherited from "human" object.
console.log(female.species)
// Output:
// 'human'

// Log the value of "isAlive" property.
// This property is inherited from "human" object.
console.log(female.isAlive)
// Output:
// true
Enter fullscreen mode Exit fullscreen mode

关于proto、原型和继承的说明

注意:speciesisAlive属性是从原始human对象继承的。如果您记录内容female对象,则这两个属性不会直接出现在其中。它们将位于__proto__对象内部。此对象引用原始对象human

你可以想象__proto__用替换human。或者,用你用作原型的任何其他对象替换它。当你使用这两个属性时,JavaScript 会查看该原型对象以获取实际值。所以,基本上,JavaScript 的female.isAlive会变成human.isAlive

这就是为什么这些属性不会直接在新对象中列出,但你仍然可以访问它们。同样,如果你更改 中的属性值,human在 中也会获得新值female。例如,如果你设置human.isAlivefalsefemale.isAlive现在也将是false

原因是,在两种情况下,你都在使用同一个属性。你正在使用human.isAlive。在一种情况下,你只是将 替换human为一个“别名”。你可以在本教程female中了解更多关于 JavaScript 中的原型和原型继承的知识

// Log the value of "isAlive" property.
// This property is inherited from "human" object.
console.log(female.isAlive)
// Output:
// true

// Change the "isAlive" property in "human" object.
human.isAlive = false

// Log the value of "isAlive" property again.
console.log(female.isAlive)
// Output:
// false
Enter fullscreen mode Exit fullscreen mode

4. Object.assign() 方法

Object.assign()方法提供了另一种在 JavaScript 中创建对象的方法。此方法与 非常相似Object.create()。此方法也通过复制现有对象来创建新对象。与 不同的是Object.create(),此方法允许您使用任意数量的源对象。

Object.create()可以使用一个对象的属性创建一个对象。Object.assign()你也可以使用多个对象的属性创建一个对象。使用此方法创建新对象很简单。它需要两个参数。第一个参数是你想要创建的新对象。

如果您不想添加任何新属性,请传入一个空对象 ( {})。否则,请传入一个包含要添加属性的对象。第二个参数是您想要用作源对象的任何对象。您的新对象将从这些源对象继承其属性。

// Create some source objects.
const lang = {
  language: 'JavaScript'
}

const job = {
  jobTitle: 'Programmer'
}

const experience = {
  experienceLevel: 'senior'
}


// Create new empty object with Object.assign() method.
// Use "lang", "job" and "experience" objects.
// First argument is an empty object to create.
// Second argument are source objects.
const coderAnonymous = Object.assign({}, lang, job, experience)

// Log the "coderAnonymous" object.
console.log(coderAnonymous)
// Output:
// {
//   language: 'JavaScript',
//   jobTitle: 'Programmer',
//   experienceLevel: 'senior'
// }


// Create new object with Object.assign() method.
// Use "lang", "job" and "experience" objects
// as source objects and also add new property "name".
// First argument is an object to create with property "name".
// Second argument are source objects.
const coderJack = Object.assign({
  // Add new property "name".
  name: 'Jack'
}, lang, job, experience) // Specify source objects.

// Log the "coderJack" object.
console.log(coderJack)
// Output:
// {
//   name: 'Jack',
//   language: 'JavaScript',
//   jobTitle: 'Programmer',
//   experienceLevel: 'senior'
// }
Enter fullscreen mode Exit fullscreen mode

No.5:函数构造函数

在 JavaScript 中创建对象的第五种方法是使用函数构造函数。这些函数构造函数看起来像常规函数。但是,它们之间存在一些差异。首先,当您使用常规函数时,您会调用它或调用它。函数构造函数则不是这样。

当你想使用函数构造函数来创建对象时,它的用法与Object()构造函数类似。你需要使用new关键字。第二个区别是,你通常使用常规函数在调用它们时执行某些操作。函数构造函数用于创建对象。

第三个区别是函数构造函数经常使用this关键字。普通函数呢?这取决于你的偏好和使用模式。不过,this在普通函数中你不太可能使用它。而在构造函数中,你会经常使用它。最后一个区别是函数构造函数的名称以大写字母开头。

让我们来看看如何创建和使用函数构造函数。首先是function关键字。接下来是函数构造函数的名称,以大写字母开头。接下来是函数构造函数的参数。这些参数定义了您希望使用构造函数创建的每个对象都具有的属性。

在函数体内部,将这些参数赋值为函数构造函数的新属性。这时就要用到this关键字了。这样,在创建函数构造函数时,就可以引用它。此外,它还允许引用使用构造函数创建的每个实例(新对象)。

当您想使用此函数构造函数时,您可以像构造函数一样使用它。在这种情况下,您还会根据函数构造函数所接受的参数传递一些参数。如果您想添加某个方法,也可以。只需确保在方法名称前Object()使用关键字即可。this

// Create function constructor called "User".
function User(name, username, email) {
  // Assign parameters as new properties of the function constructor.
  // This allows you to use <objName>.property: userJoe.name
  // and get the value of "name" property of "userJoe" object
  // and not any other instance of User, i.e. other object.
  this.name = name
  this.username = username
  this.email = email

  // Add object method.
  this.sayHi = function() {
    return `Hi, my name is ${this.name}.`
  }
}

// Use "User" function constructor to create new objects.
const userJoe = new User('Joe', 'joe123', 'joe@hello.com')
const userCathy = new User('Catherine', 'cathy', 'Catherine@hello.com')

// Log names of new users.
console.log(userJoe.name)
// Output:
// 'Joe'

console.log(userCathy.name)
// Output:
// 'Catherine'

// Log usernames of new users.
console.log(userJoe.username)
// Output:
// 'joe123'

console.log(userCathy.username)
// Output:
// 'cathy'

// Log emails of new users.
console.log(userJoe.email)
// Output:
// 'joe@hello.com'

console.log(userCathy.email)
// Output:
// 'Catherine@hello.com'

// Call the sayHi method for all new users.
console.log(userJoe.sayHi())
// Output:
// 'Hi, my name is Joe.'

console.log(userCathy.sayHi())
// Output:
// 'Hi, my name is Catherine.'
Enter fullscreen mode Exit fullscreen mode

No.6:ES6 类

最后一种创建新对象的方法也是最新的。JavaScript是在 ES6 规范中引入的。类可能看起来像是新事物,但其实不然。仔细观察,你会发现它们实际上与我们刚才讨论的函数构造函数非常相似。在底层,它们的工作方式也类似。

当你想要创建新类时,首先要输入class关键字。接下来,指定类名。之后是花括号和类体。在这里,你可以定义类应该具有的类属性和类方法。这些属性的定义方式与函数构造函数类似。

this您可以在开头使用关键字定义它们。但是,您不能直接在主体中定义它们,而是在构造函数方法中定义它们。这是一个特殊的方法,每次创建类的实例时都会调用它。创建实例本质上是基于类创建新的对象。

这也是定义类参数的地方。这些参数将用于在创建该类的新实例(副本)时向属性传递值。当要创建该类的新实例(基于该实例的新对象)时,可以使用类名和new关键字。

这与上一节中讨论函数构造函数时看到的过程相同。如果你的类接受任何参数,你现在可以将适当的值作为参数传递。你在constructor方法中定义了这些参数,并将它们赋值为类属性。

让我们使用User函数构造函数并将其编写为一个类。这将帮助您了解类和函数构造函数之间的相似之处。如果您想了解有关 JavaScript 类的更多信息,请查看我撰写的教程(第一部分第二部分)

// Create a new class "User".
class User {
  // Create constructor method
  // and define parameters for "name", "username" and "email".
  constructor(name, username, email) {
    this.name = name
    this.username = username
    this.email = email

    // Also, add one class method.
    this.sayHi = function() {
      return `Hi, my name is ${this.name}.`
    }
  }
}

// Use "User" class to create new instance, new object.
const userJill = new User('Jill', 'jill987', 'jill@hello.com')

// Log the content of userJill instance/object
console.log(userJill)
// Output:
// User {
//   name: 'Jill',
//   username: 'jill987',
//   email: 'jill@hello.com',
//   sayHi: ƒ (),
//   __proto__: User { constructor: ƒ User() }
// }

// Log the value of "name" property of "userJill".
console.log(userJill.name)
// Output:
// 'Jill'

// Log the value of "username" property of "userJill".
console.log(userJill.username)
// Output:
// 'jill987'

// Log the value of "email" property of "userJill".
console.log(userJill.email)
// Output:
// 'jill@hello.com'

// Call the sayHi method.
console.log(userJill.sayHi())
// Output:
// 'Hi, my name is Jill.'
Enter fullscreen mode Exit fullscreen mode

结论:JavaScript 中创建对象的六种方法

以上就是在 JavaScript 中创建对象的六种方式。简单回顾一下,这六种方式分别是:对象字面量、new关键字Object.create()、、Object.assign()函数构造函数和 ES6 类。希望你喜欢本教程,并学到一些新东西,帮助你成为一名更优秀的 JavaScript 开发者。

文章来源:https://dev.to/alexdevero/six-ways-to-create-objects-in-javascript-5fih
PREV
JavaScript 事件循环详解
NEXT
React 中的记忆化:简单介绍