ES6类与继承
Rio 2023-01-17
js
es6
说明
ES6 class和继承笔记总结
# class定义类
cLass定义的类,不能作为一个普通的函数进行调用
// 本质是构造函数
// 写在类中的方法本质就是写在原型里面的方法
class Student {
constructor(name,age){
this._name = name
this._age = age
}
study(score){
console.log(this.name+' '+score);
}
set name(val){
console.log("set");
this._name = val;
}
get name(){
console.log("get");
return this._name
}
}
let s1 = new Student('rio',20)
s1.study(98) // get rio 98
s1.name = 'qwe' // set
console.log(s1.name); // get qwe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# static静态方法的定义
静态方法只能由类进行调用,实例方法只能由实例对象进行调用
class Student {
constructor(name,age){
this._name = name
this._age = age
}
study(score){
console.log(this.name+' - '+score);
}
static read(){
console.log("read");
}
}
// Student.study() 报错
Student.read() // read
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# ES6继承
class Person {
constructor(name,age){
this._name = name
this._age = age
}
study(score){
console.log(this._name+' - '+score);
}
}
class Student extends Person{
constructor(name,age,id){
super(name,age);
this.id = id
}
}
let s1 = new Student("rio",20,1)
console.log(s1); // Student {_name: 'rio', _age: 20, id: 1}
s1.study(45); // rio - 45
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20