本文概要
抽象是隐藏实现细节,并只显示功能给用户的一种方式。换句话说,它忽略无关的细节,并只显示所需要的一个。
要记住的要点
- 我们不能创建抽象类的一个实例。
- 它减少了代码重复。
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>
实例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
评论前必须登录!
注册