JavaScript 抽象

JavaScript 抽象

抽象是一种隐藏实现细节,只向用户显示功能的方式。换句话说,它忽略了不相关的细节,只显示所需的内容。

记住的要点

  • 我们不能创建抽象类的实例。
  • 它减少了代码的重复。

JavaScript抽象示例

示例1

让我们来检查一下是否可以创建抽象类的实例。

<script>
//Creating a constructor function
function Vehicle()
{
    this.vehicleName= vehicleName;
    throw new Error("You cannot create an instance of Abstract class");

}
Vehicle.prototype.display=function()
{
    return this.vehicleName;
}
var vehicle=new Vehicle();
 </script>

JavaScript 抽象

示例2

让我们看一个实现抽象的示例。

<script>
//Creating a constructor function
 function Vehicle()
{
    this.vehicleName="vehicleName";
    throw new Error("You cannot create an instance of Abstract Class");
}
Vehicle.prototype.display=function()
{
    return "Vehicle is: "+this.vehicleName;
}
//Creating a constructor function
function Bike(vehicleName)
{
    this.vehicleName=vehicleName;
}
//Creating object without using the function constructor
Bike.prototype=Object.create(Vehicle.prototype);
var bike=new Bike("Honda");
document.writeln(bike.display());


 </script>

输出:

Vehicle is: Honda

示例3

在该示例中,我们使用instanceof运算符来测试对象是否引用了对应的类。

<script>
//Creating a constructor function
 function Vehicle()
{
    this.vehicleName=vehicleName;
    throw new Error("You cannot create an instance of Abstract class");
}
//Creating a constructor function
function Bike(vehicleName)
{
    this.vehicleName=vehicleName;
}
Bike.prototype=Object.create(Vehicle.prototype);
var bike=new Bike("Honda");
document.writeln(bike instanceof Vehicle);
document.writeln(bike instanceof Bike);

 </script>

输出:

true true

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程