JavaScript继承是一种机制,使无涯教程可以在现有类的基础上创建新类。它为子类提供了灵活性,以重用父类的方法和变量。
JavaScript extends关键字用于在父类的基础上创建子类。它有助于子类获取其父类的所有属性和行为。
在此示例中,扩展了 Date 对象以显示今天的日期。
<script> class Moment extends Date { constructor() { super(); }} var m=new Moment(); document.writeln("Current date:") document.writeln(m.getDate()+"-"+(m.getMonth()+1)+"-"+m.getFullYear()); </script>
输出:
Current date: 31-8-2018
再看一个示例,以显示给定日期的年份值。
链接:https://www.learnfk.comhttps://www.learnfk.com/javascript/javascript-oops-inheritance.html
来源:LearnFk无涯教程网
<script> class Moment extends Date { constructor(year) { super(year); }} var m=new Moment("August 15, 1947 20:22:10"); document.writeln("Year value:") document.writeln(m.getFullYear()); </script>
输出:
Year value: 1947
在此示例中,声明了扩展其父类属性的子类。
<script> class Bike { constructor() { this.company="Honda"; } } class Vehicle extends Bike { constructor(name,price) { super(); this.name=name; this.price=price; } } var v = new Vehicle("Shine","70000"); document.writeln(v.company+" "+v.name+" "+v.price); </script>
输出:
Honda Shine 70000
在这里,执行基于原型的继承。在这种方法中,不需要使用class和extends关键字。
<script> //Constructor function function Bike(company) { this.company=company; } Bike.prototype.getCompany=function() { return this.company; } //Another constructor function function Vehicle(name,price) { this.name=name; this.price=price; } var bike = new Bike("Honda"); Vehicle.prototype=bike; //Now Bike treats as a parent of Vehicle. var vehicle=new Vehicle("Shine",70000); document.writeln(vehicle.getCompany()+" "+vehicle.name+" "+vehicle.price); </script>
输出:
Honda Shine 70000
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)