ES6 中的继承

ES6 继承  (逼格最高,也是未来的趋势,必学必用)

知识点:
class  类
ES6给我们提供了class的语法糖,可以通过class来创建类
 1       class Person {//此行没有括号,在第二行constructor()传参
 2           constructor(name,age){
 3               this.name = name;
 4               this.age = age;
 5           }
 6           /*下面的写法就等同于把方法挂在原型上*/
 7           static say(){// 加了static 静态方法,只给类用的方法
 8               console.log('哈哈');
 9           }//方法和方法之间不用加逗号 ,
10           say(){//动态方法,给实例使用的方法
11               console.log(this.name);
12           }
13       }
14   
15       let p = new Person('成龙',20);
16       p.say();//成龙

声明子类 extends 父类名 就继承父类了

 1      class Coder extends Person {
 2          /*
 3              在子类constructor中添加属性的小技巧
 4  
 5              专属于子类的属性写在参数的前面,父类的属性放在后面
 6              这样一来,就能直接使用...arg
 7  
 8              ...arg
 9                  把函数中的多余的参数放入数组中体现出来。
10  
11          */
12          constructor(job,...arg){
13              // console.log(this)
14              super(...arg); //等同于调用父类,把多余的参数(和父类一样的属性)放到super中,达到继承父类属性的目的
15              /*
16                  在继承里,写constructor必须写super
17                  super下面才能使用this,super有暂存死区(super上面不能使用this,用了就报错)
18              */
19              this.job = job;//自己私有的属性,直接this点即可
20              console.log(arg);
21          }
22          codeing(){
23              console.log('敲代码');
24          }
25          say(){
26              console.log('哈哈');
27          }
28  
29      }
30  
31      let c = new Coder('前端','周杰伦',20);
32      let p = new Person('张杰',30);
33      // delete c.name;
34      console.log(c);
35      // c.say();
36      // p.say();
37      // c.codeing();

猜你喜欢

转载自www.cnblogs.com/MrZhujl/p/9937657.html
今日推荐