1.基本定义和使用
1 { 2 class Parent{ 3 constructor(name='zyn'){ 4 this.name=name; 5 } 6 } 7 var pp = new Parent('zyn...'); 8 console.log('构造函数实例',pp) 9 }
2.继承 extends
1 { 2 class Parent{ 3 constructor(name='zyn'){ 4 this.name=name; 5 } 6 } 7 class Child extends Parent{ 8 9 } 10 console.log('继承',new Child()) 11 }
3.继承传递参数,super
1 { 2 class Parent{ 3 constructor(name='zyn'){ 4 this.name=name; 5 } 6 } 7 class Child extends Parent{ 8 constructor(name='child'){ 9 super(name); //super中是父元素的属性列表,如果子类需要增加属性,super需要放在最前面 10 this.type='cc'; 11 } 12 } 13 console.log('继承传递参数',new Child(),new Child('hello')) 14 }
4.getter,setter
1 { 2 class Parent{ 3 constructor(name='zyn'){ 4 this.name=name; 5 } 6 get longName(){ //注意是属性,虽然写法像函数 7 return 'zz'+this.name; 8 } 9 set longName(value){ 10 this.name=value 11 } 12 } 13 let vv =new Parent(); 14 console.log('getter',vv.longName); 15 vv.longName='zzzzzHello'; 16 console.log('setter',vv.longName) 17 }
5.静态方法,通过类调用,而不是类的实例
1 { 2 // 静态方法,通过类调用,而不是类的实例 3 class Parent{ 4 constructor(name='zyn'){ 5 this.name=name; 6 } 7 static tell(){ 8 console.log('tell') 9 } 10 } 11 Parent.tell(); //tell 12 }
6.静态属性直接定义在类上
1 { 2 // 静态属性 3 class Parent{ 4 constructor(name='zyn'){ 5 this.name=name; 6 } 7 static tell(){ 8 console.log('tell') 9 } 10 } 11 12 Parent.type='test'; //静态属性直接在类上定义 13 console.log('静态属性',Parent.type) 14 }