本文概要
- 要记住的要点
- JavaScript的抽象实例
要记住的要点
- 我们不能创建抽象类的一个实例。
- 它减少了代码重复。
【JavaScript的OOPS抽象】让我们来看看我们是否可以创建抽象类与否的一个实例。
<
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
推荐阅读
- JavaScript的Cookie
- JavaScript的OOPS多态性
- JavaScript的OOPS静态方法
- JavaScript的OOPS类
- JavaScript表单验证
- javascript日期
- JavaScript的导航对象
- JavaScript的数学对象
- JavaScript的innerText属性