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 中实现抽象。

广告

© . All rights reserved.