如何在 JavaScript 中呼叫父類的建構函式?


在本文中,我們將探討物件中的建構函式。我們可以從物件的方面建立繼承,即父物件可以擁有一個或多個子物件。現在我們可以從子物件呼叫父物件的建構函式。

建構函式

這些是類的例項,通常稱為物件。JavaScript 中的 new 關鍵字使用建構函式在需要宣告或建立物件時進行呼叫。我們可以使用這些建構函式將屬性設定到物件中。

JavaScript 中的繼承

這是物件訪問另一個物件的屬性或方法的能力。這種能力稱為繼承。物件可以繼承父物件的屬性和方法。並且子物件可以擴充套件父屬性。

為了呼叫父類的建構函式,我們可以使用 super 關鍵字。建構函式方法中的 super() 方法用於呼叫父類的建構函式方法,以訪問父類的屬性和方法。

示例 1

在下面的示例中,我們建立了兩個類,即父類和子類。子類擴充套件了父類。現在,為了從父類呼叫建構函式,我們將使用 **super()** 方法,該方法將負責呼叫此建構函式並執行必要的操作。

# index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Property Descriptors</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      class Parent {
         constructor(num1) {
            this.num1 = num1;
         }
         fun() {
            console.log("Parent class method call");
         }
      }
      class Child extends Parent {
         constructor(num1, num2) {
            // Calling parent class constructor
            super(num1);
            this.num2 = num2;
         }
         fun() {
            super.fun();
            console.log("Child class method call");
         }
      }
      let obj = new Child(2, 3);
      obj.fun();
      console.log(obj);
   </script>
</body>
</html>

輸出

在成功執行上述程式後,您將在控制檯中找到與以下螢幕截圖類似的結果

示例 2

在下面的示例中,我們從子類呼叫基類的例項。由於建立的例項是基類,因此不會呼叫子類的方法。

# index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Property Descriptors</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      // Object
      const Obj = {
         property1: "Tutorials Point",
         property2: "Simply Learning"
      };
      const descriptor1 = Object
         .getOwnPropertyDescriptor(Obj, 'property1');
      const descriptor2 = Object
         .getOwnPropertyDescriptor(Obj, 'property2');
      console.log(descriptor1.configurable);
      // expected output: true
      console.log(descriptor1.enumerable);
      // expected output: true
      console.log(descriptor1.value);
      // expected output: Tutorials Point
      console.log(descriptor2.value);
      // expected output: Simply Learning
   </script>
</body>
</html>

輸出


更新於: 2022-04-22

2K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告