1.类的创建:
-
定义类
-
类的构造函数
-
类的静态方法
-
类的一般属性和方法
1 //定义类
2 class Person{
3
4 // 类的静态方法,相当于Person.test = function(){console.log("类的静态方法");}
5 static test() {
6 console.log("类的静态方法");
7
8 }
9
10 //constructor构造函数
11 constructor(name,age){
12
13 console.log("调用构造函数");
14 this.name = name;
15 this.age = age;
16 }
17
18 //类的一般方法,定义在实例对象的原型对象上,相当于Person.prototype.show = function(){console.log("this.name,this.age");}
19 show(){
20 console.log(this.name,this.age);
21
22 }
23 }
24
25 let person1 = new Person("wzh",25);
26 console.log(person1);
27
28 person1.show();
29 Person.test();
2.继承
1 //定义类
2 class Person{
3
4 // 类的静态方法,相当于Person.test = function(){console.log("类的静态方法");}
5 static test() {
6 console.log("类的静态方法");
7
8 }
9
10 //constructor构造函数
11 constructor(name,age){
12
13 console.log("调用构造函数");
14 this.name = name;
15 this.age = age;
16 }
17
18 //类的一般方法,定义在实例对象的原型对象上,相当于Person.prototype.show = function(){console.log("this.name,this.age");}
19 show(){
20 console.log(this.name,this.age);
21
22 }
23 }
24
25 let person1 = new Person("wzh",25);
26 console.log(person1);
27
28 class Child extends Person{
29
30 constructor(name,age,sex){
31 super(name,age); //调用父类构造函数构造子类
32 this.sex = sex;
33 }
34
35 //重写父类同名函数
36 show(){
37 console.log(this.name,this.age,this.sex);
38
39 }
40
41 }
42
43 let child = new Child("wzl",24,"男");
44 child.show();