在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中实现继承的方式是什么的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号