您好,欢迎访问一九零五行业门户网

es6中实现继承的方式是什么

在es6中,可利用class关键字配合extends关键字来实现继承。es6中引入了class关键字来声明类, 而class(类)可通过extends来继承父类中属性和方法,语法“class 子类名 extends 父类名{...};”。
本教程操作环境:windows7系统、ecmascript 6版、dell g3电脑。
es6中可利用class关键字配合extends关键字来实现继承
在es6中,class (类)作为对象的模板被引入,可以通过 class 关键字定义类。
es6继承
class 可以通过extends关键字实现继承
class animal {}class cat extends animal { };
上面代码中 定义了一个 cat 类,该类通过 extends关键字,继承了 animal 类中所有的属性和方法。 但是由于没有部署任何代码,所以这两个类完全一样,等于复制了一个animal类。 下面,我们在cat内部加上代码。
class cat extends animal { constructor(name, age, color) { // 调用父类的constructor(name, age) super(name, age); this.color = color; } tostring() { return this.color + ' ' + super.tostring(); // 调用父类的tostring() }}
constructor方法和tostring方法之中,都出现了super关键字,它在这里表示父类的构造函数,用来新建父类的this对象。
需要注意的是:class 关键字只是原型的语法糖, javascript 继承仍然是基于原型实现的。
class pet { constructor(name, age) { this.name = name; this.age = age; } showname() { console.log("调用父类的方法"); console.log(this.name, this.age); }}// 定义一个子类class dog extends pet { constructor(name, age, color) { super(name, age); // 通过 super 调用父类的构造方法 this.color = color; } showname() { console.log("调用子类的方法"); console.log(this.name, this.age, this.color); }}
优点:
清晰方便
缺点:
不是所有的浏览器都支持 class。
【相关推荐:javascript视频教程、web前端】
以上就是es6中实现继承的方式是什么的详细内容。
其它类似信息

推荐信息