JavaScript 中的Abstraction(抽象)
JavaScript 的抽象可以使用 abstract 类来实现。在面向对象的编程中,抽象概念允许您隐藏实现细节并仅向用户公开功能。
例如,您可以通过使用其名称访问方法,在 JavaScript 中执行 Math 对象方法,但无法查看其实现方式。以同样的方式执行 push()、pop() 等数组方法,但您不知道它是如何在内部实现的。
因此,抽象通过公开所需的功能并隐藏内部实现细节来使代码更简洁。
如何在 JavaScript 中实现抽象?
在大多数编程语言中,您可以使用 abstract 类实现抽象。抽象类仅包含方法声明,而不包含实现。此外,您需要将抽象类中声明的方法实现到子类中。此外,您不能创建抽象类的实例。
JavaScript 不允许原生创建像 Java 或 CPP 这样的抽象类,但你可以使用对象构造函数实现相同的功能。
首先,让我们使用下面的示例创建一个抽象类。
创建 Abstract 类
在下面的示例中,fruit() 函数初始化 name 属性。当任何人创建 fruit() 的实例时,constructor 属性的值将等于 '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>
输出
在上面的示例中,您学习了如何实现抽象类功能。
现在,您将通过以下示例学习扩展抽象类并实现抽象类中定义的方法。
扩展 Abstract 类
在下面的示例中,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>
输出
原型在上面的代码中实现了 getName() 方法。所以,它是隐藏的。
这样,你可以使用对象构造函数在 JavaScript 中实现抽象。