ES6参考---class类

ES6参考---class类

一、总结

一句话总结:

1、通过class定义类/实现类的继承,在类中通过constructor定义构造方法
2、通过new来创建类的实例
3、通过extends来实现类的继承,通过super调用父类的构造方法
4、重写从父类中继承的一般方法
class Person {
  //调用类的构造方法
  constructor(name, age){
      this.name = name;
      this.age = age;

  }
  //定义一般的方法
  showName(){
      console.log(this.name, this.age);
  }
}
let person = new Person('kobe', 39);
console.log(person, person.showName());

//定义一个子类
class StrPerson extends Person{
  constructor(name, age, salary){
      super(name, age);//调用父类的构造方法
      this.salary = salary;
  }
  showName(){//在子类自身定义方法
      console.log(this.name, this.age, this.salary);
  }
}
let str = new StrPerson('weide', 38, 1000000000);
console.log(str);
str.showName();

二、class类

博客对应课程的视频位置:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>12_class</title>
 6 </head>
 7 <body>
 8 </body>
 9 <!--
10 1. 通过class定义类/实现类的继承
11 2. 在类中通过constructor定义构造方法
12 3. 通过new来创建类的实例
13 4. 通过extends来实现类的继承
14 5. 通过super调用父类的构造方法
15 6. 重写从父类中继承的一般方法
16 -->
17 <script type="text/javascript">
18     class Person {
19         //调用类的构造方法
20         constructor(name, age){
21             this.name = name;
22             this.age = age;
23 
24         }
25         //定义一般的方法
26         showName(){
27             console.log(this.name, this.age);
28         }
29     }
30     let person = new Person('kobe', 39);
31     console.log(person, person.showName());
32 
33     //定义一个子类
34     class StrPerson extends Person{
35         constructor(name, age, salary){
36             super(name, age);//调用父类的构造方法
37             this.salary = salary;
38         }
39         showName(){//在子类自身定义方法
40             console.log(this.name, this.age, this.salary);
41         }
42     }
43     let str = new StrPerson('weide', 38, 1000000000);
44     console.log(str);
45     str.showName();
46 </script>
47 </html>
 
原文地址:https://www.cnblogs.com/Renyi-Fan/p/12589484.html