类和类的方法

1:定义类和定义构造函数差不多,并且很多特性也和构造函数一致

1 class Person {
2     name = 'tyy'
3 }
4 var p = new Person
5 console.log(p);
6 console.log(p.__proto__);
7 console.log(p.__proto__.__proto__);
8 console.log(p.__proto__ === Person.prototype);

 

 2:类的实例方法,类的访问器方法以及类的静态方法

实例方法:对象点调用,静态方法:类名点调用

 1 class Person {
 2     constructor(name, age, heigth, address) {
 3             this.name = name
 4             this.age = age
 5             this.heigth = heigth
 6             this._address = address
 7         }
 8         //实例方法
 9     eating() {
10         console.log('eating');
11     }
12     studying() {
13             console.log('studying');
14         }
15         //访问器方法
16     get address() {
17         console.log('我获取啦');
18         return this._address
19     }
20     set address(newaddress) {
21         console.log('我设置啦');
22         this._address = newaddress
23     }
24 
25 
26 }
27 
28 var p = new Person('tyy', 20, 1.55, '四川')
29 console.log(p.address);
30 console.log(p);
31 p.eating()
32 p.address = "四川达州"
33 console.log(p.address);
34 console.log(p);
35 p.studying()

 

 

 1 class Person {
 2     constructor(age) {
 3         this.age = age
 4     }
 5     static creat() {
 6         return new Person(Math.floor(Math.random() * 100))
 7     }
 8 }
 9 for (var i = 1; i < 50; i++) {
10     console.log(Person.creat());
11 }

 

 3:类的继承--extends

super关键字

调用 父类//父对象的构造函数 super([arguments])

调用 父类//父对象的方法 super.functionParent([arguments])

具体看例子

 1 class Person {
 2     constructor(mood, age) {
 3         this.mood = mood
 4         this.age = age
 5 
 6     }
 7     running() {
 8         console.log('running');
 9     }
10     eating() {
11         console.log('personeating');
12     }
13     static create() {
14         console.log('人物1');
15         console.log('人物2');
16         console.log('人物3');
17     }
18 }
19 //实现继承
20 class Student extends Person {
21     constructor(mood, age, height) {
22         super(mood, age)
23         this.height = height
24     }
25     studying() {
26             console.log('studying');
27         }
28         //修改父类静态方法
29     static create() {
30             super.create() //调用父类方法
31             console.log('人物2');
32             console.log('人物3');
33             console.log('人物4');
34         }
35         //修改父类实例方法
36     eating() {
37         super.eating()
38         console.log('Studenteating');
39     }
40 }
41 var stu1 = new Student('happy', 20, 1.55)
42 console.log(stu1);
43 stu1.eating()
44 Student.create()

 

posted @ 2022-03-23 08:51  沁霓  阅读(69)  评论(0)    收藏  举报