一、类的定义
1
2
3
4
5
6
7
8
|
class Parent{ constructor(name= "zhang" ){ this .name=name; } } let shi= new Parent( "v" );//类的实例 console.log( "constructor" ,shi); |
二,类的继承
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
//继承
class Parent{ constructor(name= "zhang" ){ this .name=name; } }
class Child extends Parent{ //
extends 用于继承父类Child继承 } console.log( "extend" , new Child()); //继承传递参数,child向parent传递参数,改变parent的默认参数
class Parent{ constructor(name= "zhang" ){ this .name=name; } }
class Child extends Parent{ constructor(name= "child" ){ super (name);
//super必须放在设置改变参数的前面 this .type= "child" } } console.log( "extend" , new Child( "hello" )); }
//extend
Child {name: "hello", type: "child"} |
子类必须在父类的构造函数中调用super()
,这样才有this对象,因为this对象是从父类继承下来的。而要在子类中调用父类的方法,用super
关键词可指代父类。
ES5中类继承的关系是相反的,先有子类的this,然后用父类的方法应用在this上。
ES6类继承子类的this是从父类继承下来的这个特性,使得在ES6中可以构造原生数据结构的子类,这是ES5无法做到的。
三、getter 、setter 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Parent{ constructor(name= "zhang" ){ this .name=name; }
get
long(){ return "mk" + this .name
//属性在读取时前面加上‘mk’ } set
long(value){ this .name=value;//给long这个属性赋值时会将值付给当前的name } } let v= new Parent(); console.log( "getter" ,v.long); v.long= "hello" console.log( "setter" ,v.long); |
四、静态方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
//静态方法 class Parent{ constructor(name= "zhang" ){ this .name=name; } static tell(){ console.log( "tell" ); } } Parent.tell();//静态方法通过类去调用,而不是类的实例调用。 //静态属性 class Parent{ constructor(name= "zhang" ){ this .name=name; } } Parent.type= "test" ;//静态属性没有关键词,在类定义后直接定义,类名.属性=“” console.log( "静态属性" ,Parent.type); }
ES6也可以定义类的静态方法和静态属性,静态的意思是这些不会被实例继承,不需要实例化类,就可以直接拿来用。ES6中class内部只能定义方法,不能定义属性。在方法名前加上static就表示这个方式是静态方法,而属性还是按照ES5的方式来实现。 |
es6与es5中类的比较。
举个例子,在ES5中定义一个类:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
而用ES6的写法重写一下,检测类型发现Person本质上仍然是函数:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
调用的方式都是一致的: