JavaScript抽象

JavaScript抽象 首页 / JavaScript入门教程 / JavaScript抽象

抽象是一种隐藏实现细节并仅向用户显示函数的方法。换句话说,它忽略了无关的细节,只显示了所需的细节。

要点

  • 无法创建Abstract Class抽象类的实例。
  • 它减少了代码的重复。

例子1

检查是否可以创建Abstract类的实例。

链接:https://www.learnfk.comhttps://www.learnfk.com/javascript/javascript-oops-abstraction.html

来源:LearnFk无涯教程网

<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 OOPs Abstraction

例子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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

eBPF核心技术与实战 -〔倪朋飞〕

程序员的个人财富课 -〔王喆〕

讲好故事 -〔涵柏〕

如何读懂一首诗 -〔王天博〕

操作系统实战45讲 -〔彭东〕

爆款文案修炼手册 -〔乐剑峰〕

TensorFlow 2项目进阶实战 -〔彭靖田〕

高并发系统设计40问 -〔唐扬〕

编辑训练营 -〔总编室〕

好记忆不如烂笔头。留下您的足迹吧 :)