Appearance
类
class
- class 是一种新的语法形式,是
class Name {...}
这种形式,和函数的写法完全不一样 - 两者对比,构造函数函数体的内容要放在 class 中的
constructor
函数中,constructor
即构造器,初始化实例时默认执行 - class 中函数的写法是
add() {...}
这种形式,并没有function
关键字
javascript
class Person{
constructor(name){
this.name = name;
}
getName(){
console.log(this.name)
}
}
let person = new Person('wjh');
person.getName();
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
get 与 set
getter 可以用来获取属性,setter 可以去设置属性
javascript
class Person {
constructor(){
this.hobbies = [];
}
set hobby(hobby){
this.hobbies.push(hobby);
}
get hobby(){
return this.hobbies;
}
}
let person = new Person();
person.hobby = 'aa';
person.hobby = 'bb';
console.log(person.hobby)
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
静态方法 -static
在类里面添加静态的方法可以使用 static 这个关键词,静态方法就是不需要实例化类就能使用的方法
javascript
class Person{
static add(a,b){
return a+b;
}
}
console.log(Person.add(1,x));
1
2
3
4
5
6
2
3
4
5
6
继承 extends
一个类可以继承其他的类里的东西
javascript
class Person{
constructor(name){
this.name = name;
}
}
class Teacher extends Person{
constructor(name,age){
super(name);
this.age = age;
}
}
var teacher = Teacher('wjh',8);
console.log(teacher.name,teacher.age)
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