Javascript 简明教程

JavaScript - Object Constructors

Object Constructors

JavaScript 中的 object constructor 是一个创建类实例的函数,该实例通常称为对象。当使用 new 关键字声明对象时会调用构造函数。构造函数的目的是创建对象并在存在任何对象属性时设置值。

An object constructor in JavaScript is a function that creates an instance of a class, which is typically called an object. A constructor is called when you declare an object using the new keyword. The purpose of a constructor is to create an object and set values if there are any object properties present.

有两种方法可以在 JavaScript 中创建对象的模板——使用类和使用对象构造函数。

There are two ways to create a template for the object in JavaScript - using a class and using an object constructor.

每当你需要使用相同的语法创建多个对象时,你需要一个对象的模板。例如,你正在管理汽车库存。因此,每次都使用对象字面量来创建新对象并不是一个好主意。在这些情况下,你需要使用对象构造函数。

Whenever you need to create multiple objects with the same syntax, you require a template for the object. For example, you are managing the car inventory. So, it is not a good idea to create a new object every time using the object literal. In such cases, you need to use the object constructors.

对象构造函数的主要好处是你可以重复使用代码。

The main benefit of the object constructors is that you can reuse the code.

Syntax

你可以遵循以下语法来使用对象构造函数创建对象。

You can follow the syntax below to use the object constructor to create an object.

function Funcname(p1, p2, ... , pN) {
   this.prop1 = p1;
}
const obj = new Funcname(args);

在上述语法中,Funcname() 是一个构造函数,你可以用任何有效的标识符替换 Funcname。

In the above syntax, Funcname() is a constructor function, and you can replace any valid identifier with the Funcname.

p1、p2、……和 pN 是你可以在函数体中使用的参数。你需要在创建对象时将参数传递给构造函数。

A p1, p2, …, and pN are parameters you can use inside the function body. You need to pass arguments to the constructor while creating the object.

“this”关键字表示你正在使用的函数上下文。这里,“this”关键字指的是对象的当前实例。

The 'this' keyword represents the function context you are using. Here, the 'this' keyword refers to the current instance of the object.

要创建对象,你可以将函数构造函数与“new”关键字一起使用。

To create an object, you can use the function constructor with a 'new' keyword.

Example: Creating an object using a constructor function

在下面的示例中,我们创建了一个 Tree() 函数。在函数体中,我们初始化 name 和 age 属性。

In the example below, we have created a Tree() function. In the function body, we initialize the name and age properties.

然后,我们使用带有“new”关键字的函数名称来创建 Tree() 构造函数的对象。

After that, we use the function name with a 'new' keyword to create an object of the Tree() constructor.

<html>
<body>
  <p id = "output"> </p>
  <script>

    function Tree() {
      this.name = "palm";
      this.age = 5;
    }
    const tree1 = new Tree();
    document.getElementById("output").innerHTML =
    "name = " + tree1.name + ", age = " + tree1.age;

  </script>
</body>
</html>
name = palm, age = 5

Example: Constructor function with parameters

在下面的示例中,Bike() 函数接收三个参数。在函数体中,我们使用参数初始化属性。

In the example below, the Bike() function takes three parameters. In the function body, we initialize the properties using the parameters.

然后,我们使用 Bike() 构造函数用不同的值创建了 bike1 和 bike2 对象。在输出中,你可以观察对象属性值。

After that, we created bike1 and bike2 objects with different values using the Bike() constructor. In the output, you can observe the object property values.

<html>
<body>
  <p id = "output1">The bike1 object is : </p>
  <p id = "output2">The bike2 object is :  </p>
  <script>

    function Bike(name, speed, gear) {
      this.name = name;
      this.speed = speed;
      this.gear = gear;
    }

    const bike1 = new Bike("Honda", 100, 4);
    const bike2 = new Bike("Yamaha", 200, 6);
    document.getElementById("output1").innerHTML += JSON.stringify(bike1);
    document.getElementById("output2").innerHTML += JSON.stringify(bike2);

  </script>
</body>
</html>
The bike1 object is : {"name":"Honda","speed":100,"gear":4}

The bike2 object is : {"name":"Yamaha","speed":200,"gear":6}

通过这种方式,你可以使用对象构造器重用对象语法代码,并创建多个相同类型的对象。

In this way, you can use the object constructor to reuse the object syntax code and create multiple objects of the same type.

Adding a Property or Method to a Constructor

你已在“对象”章节中了解到如何使用点号或方括号表示法向对象添加属性或方法。但是,如果你希望向对象构造器添加属性或方法,该怎么办?

You learned to add a property of method using the dot or square bracket notation into the object in the Objects chapter. But what if you want to add a property or method to the object constructor?

对象构造器不允许你在定义属性或方法后添加它们。因此,你必须始终在定义时添加必需的属性和方法。让我们通过下面的示例了解它。

The object constructor doesn’t allow you to add the property or method after defining it. So, you always need to add the required properties and methods while defining it. Let’s understand it via the example below.

Example

以下示例演示如何向对象构造器中添加方法和属性。我们在 houseAddress() 构造函数中添加了三个属性和 getFullAddress() 方法。

The below example demonstrates adding methods and properties into the object constructor. We added the three properties and the getFullAddress() method in the houseAddress() constructor function.

此外,我们通过将该对象用作引用来执行该方法。

Also, we have executed the method by taking the object as a reference.

<html>
<body>
  <p id = "output1">The house object is  </p>
  <p id = "output2">The full address of the house is  </p>
  <script>
    function HouseAddress(no, street, city) {
      // Adding properties
      this.houseNo = no,
      this.street = street,
      this.city = city;
      // Adding a method
      this.getFullAddress = function () {
        return this.houseNo + ", " + this.street + ", " + this.city;
      };
    }
    const house = new HouseAddress(20, "Cooper Square", "New York");
    document.getElementById("output1").innerHTML += JSON.stringify(house);
    document.getElementById("output2").innerHTML += house.getFullAddress();
  </script>
</body>
</html>
The house object is {"houseNo":20,"street":"Cooper Square","city":"New York"}

The full address of the house is 20, Cooper Square, New York

如果你按如下所示添加方法或属性。它将被添加到特定对象中,但不会添加到构造函数中。

If you add the method or property as shown below. It will be added to the particular object but not to the constructor function.

Obj.prop = 20;

使用对象构造器创建的其他对象不包含 prop 属性,因为它仅被添加到 obj 对象中。

Other objects created using the object constructor don’t contain the prop property as it is added to the obj object only.

JavaScript Object Prototype

在 JavaScript 中,每个对象默认包含 prototype 属性,对象构造器也是一种对象。因此,你可以在对象原型中添加属性或方法。

In JavaScript, each object contains the prototype property by default, and the object constructor is also one kind of object. So, you can add properties or methods to the object prototype.

Syntax

你可以按照以下语法向对象构造器原型添加属性或方法。

You can follow the syntax below to add properties or methods to the object constructor prototype.

obj.prototype.name = value;

在以上语法中,“obj” 是你需要在其中添加属性或方法的对象构造器。

In the above syntax, 'obj' is an object constructor in which you need to add a property or method.

“name”是属性或方法名称。

The 'name' is a property or method name.

对于属性,你可以用实际值替换“value”;对于方法,你可以用函数表达式替换“value”。

For the property, you can replace a 'value' with an actual value; for the method, you can replace a 'value' with a function expression.

Example

在以下示例中,我们已将 BikeDetails() 方法添加到 Bike() 构造器的原型中。

In the example below, we have added the BikeDetails() method to the prototype of the Bike() constructor.

可以使用 Bike() 构造器的任何对象执行 BikDetails() 方法。但是,当打印 bike1 和 bike2 对象时,它不会显示 BikeDetails() 方法,因为它被添加到原型中。

The BikDetails() method can be executed using any object of the Bike() constructor. However, when you print the bike1 and bike2 objects, it won’t show you BikeDetails() method as it is added in the prototype.

<html>
<body>
  <p id = "output1">The bike1 details is: </p>
  <p id = "output2">The bike2 details is: </p>
  <script>
    function Bike(name, speed, gear) {
      this.name = name;
      this.speed = speed;
      this.gear = gear;
    }
    Bike.prototype.BikeDetails = function () {
      return this.name + ", " + this.speed + ", " + this.gear + "<br>";
    };
    const bike1 = new Bike("Honda", 100, 4);
    const bike2 = new Bike("Yamaha", 200, 6);
    document.getElementById("output1").innerHTML += bike1.BikeDetails();
    document.getElementById("output2").innerHTML += bike2.BikeDetails();
  </script>
</body>
</html>
The bike1 details is: Honda, 100, 4

The bike2 details is: Yamaha, 200, 6

Built-in Object Constructors in JavaScript

JavaScript 包含生成器,我们已将它们列在下面的表中。

JavaScript contains a built-in constructor, which we have listed in the below table.

Sr. No.

Constructor

Description

Example

1

Array

To create an array.

new Array()

2

String

To create a string.

new String("Hello")

3

Number

To create a number.

new Number(92)

4

Boolean

To create a boolean.

new Boolean(true)

5

Set

To create a new set.

new Set()

6

Map

To create a new map.

new Map()

7

Object

To create a new object.

new Object()

8

Function

To create a new function.

new Function("x", "return x * x;")

9

Date

To create an instance of Date object.

new Date()

10

RegExp

To create a new regular expression.

new RegExp("\\d+")

11

Error

To create a new error.

new Error("new error.")

12

Symbol

To create a symbol.

Symbol("description")