es6中实现继承的方式是什么
时间:2022-04-11 16:43
在es6中,可利用class关键字配合extends关键字来实现继承。ES6中引入了class关键字来声明类, 而class(类)可通过extends来继承父类中属性和方法,语法“class 子类名 extends 父类名{...};”。 本教程操作环境:windows7系统、ECMAScript 6版、Dell G3电脑。 es6中可利用class关键字配合extends关键字来实现继承 在ES6中,class (类)作为对象的模板被引入,可以通过 class 关键字定义类。 es6继承 Class 可以通过extends关键字实现继承 上面代码中 定义了一个 Cat 类,该类通过 extends关键字,继承了 Animal 类中所有的属性和方法。 但是由于没有部署任何代码,所以这两个类完全一样,等于复制了一个Animal类。 下面,我们在Cat内部加上代码。 constructor方法和toString方法之中,都出现了super关键字,它在这里表示父类的构造函数,用来新建父类的this对象。 需要注意的是:class 关键字只是原型的语法糖, JavaScript 继承仍然是基于原型实现的。 优点: 清晰方便 缺点: 不是所有的浏览器都支持 class。 【相关推荐:javascript视频教程、web前端】 以上就是es6中实现继承的方式是什么的详细内容,更多请关注gxlsystem.com其它相关文章!class Animal {}
class Cat extends Animal { };
class Cat extends Animal {
constructor(name, age, color) {
// 调用父类的constructor(name, age)
super(name, age);
this.color = color;
}
toString() {
return this.color + ' ' + super.toString(); // 调用父类的toString()
}
}
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);
}
}