es6声明类实现继承

29次阅读

共计 444 个字符,预计需要花费 2 分钟才能阅读完成。

class 声明一个 animal 类 (对象):
class Animal{
constructor(){// 这个 constructor 方法内定义的方法和属性是实例化对象自己的,不共享;construstor 外定义的方法和属性是所有实例对象(共享)可以调用的
this.type = ‘animal’ //this 关键字代表 Animal 对象的实例对象
}
says(say){
console.log(this.type+’ says ‘ +say);
}
}
let animal = new Animal();
animal.says(‘hello’);// 控制台输出‘animal says hello’
这里声明一个 Cat 类,来继承 Animal 类的属性和方法
class Cat extends Animal(){
constructor(){
super();//super 关键字,用来指定父类的实例对象
this.type = ‘cat’;
}
}
let cat = new Cat();
cat.says(‘hello’);// 输出‘cat says hello’

正文完
 0