如何在JavaScript中创建对象

by Kaashan Hussain

由Kaashan Hussain

We all deal with objects in one way or another while writing code in a programming language. In JavaScript, objects provide a way for us to store, manipulate, and send data over the network.

在用编程语言编写代码时,我们都以一种或另一种方式处理对象。 在JavaScript中,对象为我们提供了一种通过网络存储,操作和发送数据的方式。

There are many ways in which objects in JavaScript differ from objects in other mainstream programming languages, like Java. I will try to cover that in a another topic. Here, let us only focus on the various ways in which JavaScript allows us to create objects.

JavaScript中的对象与其他主流编程语言(例如Java)中的对象有很多不同的方式。 我将尝试在另一个主题中进行介绍。 在这里,让我们仅关注JavaScript允许我们创建对象的各种方式。

In JavaScript, think of objects as a collection of ‘key:value’ pairs. This brings to us the first and most popular way we create objects in JavaScript.

在JavaScript中,将对象视为“键:值”对的集合。 这给我们带来了在JavaScript中创建对象的第一种也是最流行的方式。

Let’s get this started.

让我们开始吧。

1.使用对象文字语法创建对象 (1. Creating objects using object literal syntax)

This is really simple. All you have to do is throw your key value pairs separated by ‘:’ inside a set of curly braces({ }) and your object is ready to be served (or consumed), like below:

这真的很简单。 您所要做的就是将键值对以':'分隔在一组花括号({})中,然后就可以使用(或使用)对象了,如下所示:

const person = {
  firstName: 'testFirstName',
  lastName: 'testLastName'
};

This is the simplest and most popular way to create objects in JavaScript.

这是用JavaScript创建对象的最简单,最流行的方法。

2.使用“ new”关键字创建对象 (2. Creating objects using the ‘new’ keyword)

This method of object creation resembles the way objects are created in class-based languages, like Java. By the way, starting with ES6, classes are native to JavaScript as well and we will look at creating objects by defining classes towards the end of this article. So, to create an object using the ‘new’ keyword, you need to have a constructor function.

这种对象创建方法类似于使用基于类的语言(例如Java)创建对象的方式。 顺便说一下,从ES6开始,类也是JavaScript固有的,我们将在本文结尾处通过定义类来研究创建对象。 因此,要使用'new'关键字创建对象,您需要具有构造函数。

Here are 2 ways you can use the ‘new’ keyword pattern —

您可以通过以下两种方式使用“新”关键字模式-

a) Using the ‘new’ keyword with’ in-built Object constructor function

a)对内置对象构造函数使用'new'关键字

To create an object, use the new keyword with Object() constructor, like this:

要创建一个对象,请将new关键字与Object()构造函数一起使用,如下所示:

const person = new Object();

Now, to add properties to this object, we have to do something like this:

现在,要向该对象添加属性,我们必须执行以下操作:

person.firstName = 'testFirstName';
person.lastName = 'testLastName';

You might have figured that this method is a bit longer to type. Also, this practice is not recommended as there is a scope resolution that happens behind the scenes to find if the constructor function is built-in or user-defined.

您可能已经发现此方法的键入时间更长。 另外,不建议使用此方法,因为在幕后会发生范围解析,以查找构造函数是内置的还是用户定义的。

b) Using ‘new’ with user defined constructor function

b)与用户定义的构造函数一起使用'new'

The other problem with the approach of using the ‘Object’ constructor function result from the fact that every time we create an object, we have to manually add the properties to the created object.

使用“对象”构造函数的方法的另一个问题是由于每次创建对象时,我们都必须手动将属性添加到创建的对象中。

What if we had to create hundreds of person objects? You can imagine the pain now. So, to get rid of manually adding properties to the objects, we create custom (or user-defined) functions. We first create a constructor function and then use the ‘new’ keyword to get objects:

如果我们必须创建数百个人对象怎么办? 您现在可以想象痛苦。 因此,为了摆脱向对象手动添加属性的麻烦,我们创建了自定义(或用户定义)函数。 我们首先创建一个构造函数,然后使用'new'关键字获取对象:

function Person(fname, lname) {
  this.firstName = fname;
  this.lastName = lname;
}

Now, anytime you want a ‘Person’ object, just do this:

现在,只要您想要“ Person”对象,就可以这样做:

const personOne = new Person('testFirstNameOne', 'testLastNameOne');
const personTwo = new Person('testFirstNameTwo', 'testLastNameTwo');
3.使用Object.create()创建新对象 (3. Using Object.create() to create new objects)

This pattern comes in very handy when we are asked to create objects from other existing objects and not directly using the ‘new’ keyword syntax. Let’s see how to use this pattern. As stated on MDN:

当要求我们从其他现有对象创建对象,而不是不直接使用'new'关键字语法时,此模式非常方便。 让我们看看如何使用此模式。 如MDN所述

The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.

Object.create()方法使用现有对象作为新创建的对象的原型来创建新对象。

To understand the Object.create method, just remember that it takes two parameters. The first parameter is a mandatory object that serves as the prototype of the new object to be created. The second parameter is an optional object which contains the properties to be added to the new object.

要了解Object.create方法,只需记住它需要两个参数。 第一个参数是强制性对象,用作要创建的新对象的原型。 第二个参数是一个可选对象,其中包含要添加到新对象的属性。

We will not deep dive into prototypes and inheritance chains now to keep our focus on the topic. But as a quick point, you can think of prototypes as objects from which other objects can borrow properties/methods they need.

现在,我们将不再深入探讨原型和继承链来使我们专注于该主题。 但是,很快,您可以将原型视为对象,其他对象可以从中借用所需的属性/方法。

Imagine you have an organization represented by orgObject

假设您有一个由orgObject代表的组织

const orgObject = { company: 'ABC Corp' };

And you want to create employees for this organization. Clearly, you want all the employee objects.

您想为此组织创建员工。 显然,您需要所有员工对象。

const employee = Object.create(orgObject, { name: { value: 'EmployeeOne' } });

console.log(employee); // { company: "ABC Corp" }
console.log(employee.name); // "EmployeeOne"
4.使用Object.assign()创建新对象 (4. Using Object.assign() to create new objects)

What if we want to create an object that needs to have properties from more than one object? Object.assign() comes to our help.

如果我们想创建一个需要具有多个对象属性的对象,该怎么办? Object.assign()可以帮助我们。

As stated on MDN:

MDN所述

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Object . assign () Object . assign ()方法用于将所有可枚举的自身属性的值从一个或多个源对象复制到目标对象。 它将返回目标对象。

Object.assign method can take any number of objects as parameters. The first parameter is the object that it will create and return. The rest of the objects passed to it will be used to copy the properties into the new object. Let’s understand it by extending the previous example we saw.

Object . assign Object . assign方法可以使用任意数量的对象作为参数。 第一个参数是它将创建并返回的对象。 传递给它的其余对象将用于将属性复制到新对象中。 让我们通过扩展前面看到的示例来了解它。

Assume you have two objects as below:

假设您有两个对象,如下所示:

const orgObject = { company: 'ABC Corp' }
const carObject = { carName: 'Ford' }

Now, you want an employee object of ‘ABC Corp’ who drives a ‘Ford’ car. You can do that with the help of Object.assign as below:

现在,您需要一个驾驶“福特”汽车的“ ABC Corp”员工对象。 您可以在Object.assign的帮助下进行以下操作:

const employee = Object.assign({}, orgObject, carObject);

const employee = Object.assign({}, orgObject, carObject);

Now, you get an employee object that has company and carName as its property.

现在,您将获得一个拥有companycarName作为其属性的employee对象。

console.log(employee); // { carName: "Ford", company: "ABC Corp" }
5.使用ES6类创建对象 (5. Using ES6 classes to create objects)

You will notice that this method is similar to using ‘new’ with user defined constructor function. The constructor functions are now replaced by classes as they are supported through ES6 specifications. Let’s see the code now.

您会注意到,此方法类似于将“ new”与用户定义的构造函数一起使用。 ES6规范支持将构造函数替换为类。 现在看一下代码。

class Person {
  constructor(fname, lname) {
    this.firstName = fname;
    this.lastName = lname;
  }
}

const person = new Person('testFirstName', 'testLastName');

console.log(person.firstName); // testFirstName
console.log(person.lastName); // testLastName

These are all the ways I know to create objects in JavaScript. I hope you enjoyed this post and now understand how to create objects.

这些都是我所知道的在JavaScript中创建对象的方式。 希望您喜欢这篇文章,现在了解如何创建对象。

Thanks for your time for reading this article. If you liked this post and it was helpful to you, please click the clap ? button to show your support. Keep learning more!

感谢您抽出宝贵的时间阅读本文。 如果您喜欢这篇文章,并且对您有所帮助,请单击鼓掌? 按钮以显示您的支持。 继续学习!

翻译自: https://www.freecodecamp.org/news/a-complete-guide-to-creating-objects-in-javascript-b0e2450655e8/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值