-
Notifications
You must be signed in to change notification settings - Fork 162
/
es6中类的继承.js
56 lines (46 loc) · 1.17 KB
/
es6中类的继承.js
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Animal{//es6提供了类,只能new
//实现抽象类
constructor(){
// if(new.target === Animal){
// throw new Error("not new Animal");
// }
//实例上的属性和方法
this._type = "animal";
this.age = 20;
}
//类的原型prototype对象上的方法
eat(){
console.log('eat..');
}
//静态属性
static get num(){
return "num";
}
}
/*
(1)父类静态属性和静态方法的继承
Tiger.__proto__ = Animal;//改变Tiger的__proto__指向,修改其父类的原型指向,实现静态属性和静态方法的继承
(2)父类原型上的属性和实例方法的继承
Tiger.prototype = Object.create(Animal.prototype);
(3)父类实例属性和实例方法的继承
Animal.call(this);
*/
class Tiger extends Animal{
constructor(){//使用this之前必须调用super
//实例属性和实例方法
super();//Animal.call(this)
};
static parentNum(){
return super.num;//super指向父类自身
};
eat(){
super.eat();//super指向父类的原型
}
}
let tiger = new Tiger('tiger1');
//调用实例属性
console.log(tiger.age);//20
//调用原型方法
tiger.eat();//eat..
//调用静态方法
console.log(Tiger.parentNum());//num