class Person { constructor(name,age) { this.name = name; this.age = age; } showInfo() { console.log(this.name,this.age) } static showName() { console.log('这个人活了'); } } var person = new Person('高冷俊',22); person.showInfo(); Person.showName();
类中的方法不需要带 function 关键字。类中的方法前添加 static 关键字表示该方法是一个静态方法。静态方法无法通过实例调用,只能通过类调用
class Animal { constructor(name) { this.name = name; } showName() { console.log(this.name); } static die() { console.log('这个动物死了'); } } class Mouse extends Animal { //extends关键字告诉该类属于某类的子类 constructor(name,color) { super(name); //使用父类属性 this.color = color; } showInfo() { console.log(this.name,this.color); } } var m = new Mouse('jerry','brown'); m.showName(); m.showInfo();
通过 extends 关键字告诉该类继承其它类,类中使用 super () 继承父类属性