JavaScript - 抽象
JavaScript 中的抽象
JavaScript 中的抽象可以通过使用抽象类来实现。在面向对象编程中,抽象概念允许您隐藏实现细节,仅向用户公开功能。
例如,您可以在 JavaScript 中通过使用方法名称访问方法来执行 Math 对象的方法,但无法了解其实现方式。同样,您可以执行数组方法,例如 push()、pop() 等,但您不知道其内部是如何实现的。
因此,抽象通过公开所需功能并隐藏内部实现细节,使代码更加简洁。
如何在 JavaScript 中实现抽象?
在大多数编程语言中,您可以使用抽象类来实现抽象。抽象类仅包含方法声明,而不包含实现。此外,您需要将抽象类中声明的方法实现到子类中。而且,您无法创建抽象类的实例。
JavaScript 本身不允许像 Java 或 CPP 那样创建抽象类,但您可以使用对象构造函数实现相同的功能。
首先,让我们使用以下示例创建一个抽象类。
创建抽象类
在下面的示例中,fruit() 函数初始化 name 属性。当任何人创建 fruit() 的实例时,构造函数属性的值将等于水果的值。因此,我们抛出一个错误来阻止创建水果的实例。
此外,我们在原型中添加了 getName() 方法。之后,我们创建了 fruit() 构造函数的实例,您可以在输出中观察到错误。
<html>
<body>
<div id = "output"> </div>
<script>
try {
// 对象构造函数
function fruit() {
this.name = "Fruit";
if (this.constructor === fruit) {// 阻止对象实例
throw new Error("You can't create the instance of the fruit.");
}
}
// 原型中的实现方法
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">这种水果的名字是: </div>
<script>
// Abstract class
function fruit() {
this.name = "Fruit";
if (this.constructor === fruit) { // 阻止对象实例
throw new Error("You can't create the instance of the fruit.");
}
}
// 原型中的实现方法
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>
输出
这种水果的名字是: Apple
在上面的代码中,原型实现了 getName() 方法。因此,它是隐藏的。
这样,你就可以使用对象构造函数在 JavaScript 中实现抽象。

