JavaScript - 抽象



JavaScript 中的抽象

JavaScript 中的抽象可以透過抽象類實現。在面向物件程式設計中,抽象的概念允許您隱藏實現細節,只向用戶公開功能。

例如,您可以透過使用其名稱訪問方法來執行 JavaScript 中的 Math 物件方法,但看不到它是如何實現的。同樣,像 push()、pop() 等陣列方法可以執行,但您不知道它在內部是如何實現的。

因此,抽象透過公開所需的功能並隱藏內部實現細節來使程式碼更簡潔。

如何在 JavaScript 中實現抽象?

在大多數程式語言中,您可以使用抽象類來實現抽象。抽象類只包含方法宣告,而不包含實現。此外,您需要將抽象類中宣告的方法實現到子類中。此外,您不能建立抽象類的例項。

JavaScript 本身不允許像 Java 或 CPP 那樣建立抽象類,但您可以使用物件建構函式來實現相同的功能。

首先,讓我們使用下面的示例建立一個抽象類。

建立抽象類

在下面的示例中,fruit() 函式初始化 name 屬性。當任何人建立 fruit() 的例項時,建構函式屬性的值將變為等於 'fruit'。因此,我們丟擲一個錯誤以防止建立 fruit 的例項。

此外,我們已將 getName() 方法新增到原型中。之後,我們建立 fruit() 建構函式的例項,您可以在輸出中觀察到錯誤。

<html>
<body>
   <div id = "output"> </div>
   <script>
      try {
         // Object constructor
         function fruit() {
            this.name = "Fruit";
            if (this.constructor === fruit) {// Preventing the instance of the object
               throw new Error("You can't create the instance of the fruit.");
            }
         }
         // Implementing method in the prototype
         fruit.prototype.getName = function () {
            return this.name;
         }
         const apple = new fruit();
      } catch (error) {
         document.getElementById("output").innerHTML = error;
      }
   </script>
</body>
</html>

輸出

Error: You can't create the instance of the fruit.

在上面的示例中,您學習瞭如何實現抽象類的功能。

現在,您將學習透過下面的示例擴充套件抽象類實現抽象類中定義的方法。

擴充套件抽象類

在下面的示例中,fruit() 建構函式與上面的示例類似。我們已實現 Apple() 建構函式,初始化 name 屬性。

之後,我們使用 Object.create() 方法將 fruit() 函式的原型分配給 Apple() 函式。這意味著 Apple() 函式繼承了 fruit() 類的屬性和方法。

之後,我們建立了 Apple() 類的例項並呼叫了 getName() 方法。

<html>
<body>
   <div id = "output">The name of the fruit is: </div>
   <script>
      // Abstract class
      function fruit() {
         this.name = "Fruit";
         if (this.constructor === fruit) { // Preventing the instance of the object
            throw new Error("You can't create the instance of the fruit.");
         }
      }

      // Implementing method in the prototype
      fruit.prototype.getName = function () {
         return this.name;
      }

      // Child class
      function Apple(fruitname) {
         this.name = fruitname;
      }

      // Extending the Apple class with the fruit class
      Apple.prototype = Object.create(fruit.prototype);

      const apple = new Apple("Apple");
      document.getElementById("output").innerHTML += apple.getName();
   </script>
</body>
</html>

輸出

The name of the fruit is: Apple

原型在上面的程式碼中實現了 getName() 方法。因此,它是隱藏的。

透過這種方式,您可以使用物件建構函式在 JavaScript 中實現抽象。

廣告