Javascript 简明教程

JavaScript - new Keyword

JavaScript 中的 new 关键字用于创建具有构造函数的对象的实例。使用新关键字,我们可以创建自定义的对象类型乃至内置对象类型的实例。我们可以创建类、原型或构造函数的实例。

The new keyword in JavaScript is used to create an instance of the object that has constructor function. Using new keyword, we can create the instances of a user-defined as well as built-in object types. We can create instances of the classes, prototype, or constructor functions.

当使用 new 关键字调用 JavaScript 函数时,函数将被用作构造函数。new 关键字将执行以下操作:

When a JavaScript function is called with new keyword, the function is used as constructor. The new keyword will do the following:

  1. Creates a blank/ empty JavaScript object.

  2. Sets its prototype for inheritance.

  3. Binds this variable internally with newly created object.

  4. Executes the constructor function using new crated object whenever this is used.

  5. Returns newly created object, unless the contractor function returns a non-null object reference.

new 关键字也用于创建内置 JavaScript 对象(如 String、Boolean、Number 等)的实例。

The new keyword is also used to create an instance of the built-in JavaScript objects like String, Boolean, Number, etc.

Syntax

在 JavaScript 中使用 new 关键字的语法如下 –

The syntax to use the new keyword in JavaScript is as follows –

new Constructor(arguments);

Parameters

  1. Constructor − It is the name of the constructor function or class name.

  2. arguments −It can be multiple arguments to initialize the object properties with them.

Return Value

  1. It returns the newly created object if the constructor function returns nothing or a primitive value.

  2. It returns the value that is returned by constructor function if constructor returns a non-primitive value.

Using 'new' keyword with Function Constructor

若要使用函数作为构造函数,我们应调用函数,并将 new 关键字置于函数名前。

To use a function as a constructor, we should call the function with new keyword placing it before the function name.

我们可以使用函数构造函数定义多个对象。函数构造函数用作对象的原型。

We can define multiple objects using function constructor. The function constructor works as the object’s prototype.

按照以下语法来使用“new”关键字和构造函数以定义对象。

Follow the syntax below to use the 'new' keyword and constructor function to define the object.

new FuncName(arguments);

Example

我们在以下代码中定义了 Watch() 构造函数。

We have defined the Watch() constructor function in the code below.

Watch() 构造函数初始化了品牌、价格和类型属性。

The Watch() constructor function initializes the brand, price, and type properties.

之后,我们创建了 Watch() 函数的两个新实例,并将其打印到了输出中。

After that, we have created two new instances of the Watch() function and printed them in the output.

<html>
<body>
   <div id = "output"> </div>
   <script>
      function Watch(brand, price, type) {
      this.brand = brand;
      this.price = price;
      this.type = type;
   }
   const titan = new Watch('titen', 4000, 'analog');
   const sonata = new Watch('sonata', 3000, 'digital');
   document.getElementById('output').innerHTML +=
   "The titan object is: " + JSON.stringify(titan) + "<br>" +
   "The sonata object is: " + JSON.stringify(sonata);
</script>
</body>
</html>
The titan object is: {"brand":"titen","price":4000,"type":"analog"}
The sonata object is: {"brand":"sonata","price":3000,"type":"digital"}

Example

在以下代码中,我们定义了 Laptop() 构造函数,以此初始化与笔记本电脑相关的各种属性。此外,我们还定义了 getLaptop() 函数,用于打印笔记本电脑的详细信息。

In the below code, we have defined the Laptop() constructor function, initializing various properties related to the laptop. Also, we have defined the getLaptop() function, which prints the laptop details.

之后,我们创建了 Laptop() 对象的两个实例,并对两个实例都使用了 getLaptop() 方法。通过这种方式,可以为不同的对象共享单个方法。

After that, we created the two instances of the Laptop() object and used the getLaptop() method with both. In this way, you can share single methods with different objects.

<html>
<body>
<div id = "output"> </div>
   <script>
   const output = document.getElementById('output');
   function Laptop(brand, model, processor) {
	  this.brand = brand;
	  this.model = model;
	  this.processor = processor;
	  this.getLaptop = function () {
	     output.innerHTML += this.brand + ", " +
		 this.model + ", " + this.processor + "<br>";
      }
   }
   const HP = new Laptop('HP', "VIKING", "i7");
   const Dell = new Laptop('Dell', "Inspiron", "i5");
   HP.getLaptop();
   Dell.getLaptop();
   </script>
</body>
</html>
HP, VIKING, i7
Dell, Inspiron, i5

Using 'new' keyword with Class

还可以用 new 关键字来定义类的实例。类还为对象提供蓝图。

You can also use the new keyword to define the instance of a class. The class also provides the blueprint for the object.

在 ES6 之前,构造函数用于定义对象的模板。在 ES6 之后,类用于定义对象的模板。

Before ES6, the constructor function was used to define the template for the object. After ES6, classes are used to define the template for the object.

Example

在以下示例中,我们定义了“WindowClass”类。在“WindowClass”中,我们添加了用于初始化属性的构造函数。此外,还在类中添加了 getDetails() 方法。

In the below example, we have defined the 'WindowClass class. In the 'WindowClass' we have added the constructor to initialize the properties. We have also added the getDetails() method in the class.

之后,我们使用“new”关键字后跟类名称来定义 WindowClass 对象。

After that, we used the 'new' keyword followed by the class name to define an object of the WindowClass.

接下来,在类实例上调用 getDetails() 方法。

Next, we invoke the getDetails() method on the instance of the class.

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById('demo')
      class WindowClass {
         constructor(color, size, type) {
            this.color = color;
            this.size = size;
            this.type = type;
         }
         getDetails = function () {
            output.innerHTML =
	        "Color: " + this.color + "<br>" +
            "Size: " + this.size + "<br>" +
            "Type: " + this.type;
         }
      }
      // Creating the instance of WindowClass class
      const window1 = new WindowClass('blue', 'small', 'wooden');
      // Calling function object
      window1.getDetails();
   </script>
</body>
</html>
Color: blue
Size: small
Type: wooden

Using 'new' keyword with built-in object

还可以使用“new”关键字来定义具有构造函数的内置对象的实例。

You can also use the 'new' keyword to define the instance of the built-in object having constructor functions.

按照以下语法来创建内置对象 Number 的实例。

Follow the syntax below to create an instance of the built-in object Number.

const num = new Number(10);

在以上语法中,我们已将数字值作为 Number() 构造函数的参数传递。

In the above syntax, we have passed the numeric value as an argument of the Number() constructor.

Example

在以下代码中,我们使用了 Number() 和 String() 构造函数以及 new 关键字来定义数字对象和字符串对象。

In the code below, we have used the Number() and String() constructors with a new keyword to define the numeric and string objects.

之后,我们使用“typeof”运算符来检查 num 和 str 变量的类型。在输出中,可以看到 num 和 str 变量的类型都是对象。

After that, we used the 'typeof' operator to check the type of num and str variables. In the output, you can see that the num and str variable type is an object.

<html>
<body>
   <div id = "output"> </div>
   <script>
      const num = new Number(10);
      const str = new String("Hello");
      document.getElementById("output").innerHTML =
	  "num = " + num + ", typeof num " + typeof num + "<br>" +
      "str = " + str + ", typeof str " + typeof str;
   </script>
</body>
</html>
num = 10, typeof num object
str = Hello, typeof str object