# 类
类使用基于原型的继承
# 1、构造函数和 new.target
在函数体内,可以通过一个特殊表达式 new.target 判断函数是否作为构造函数被调用了。如果该表达式的值有定义,就说明函数是作为构造函数,通过 new 关键字调用的。
# 2、instanceof
instanceof 操作符验证 Obj.prototype
# 3、使用 class 和 extends
class Range {
constructor(a, b) {
this.a = a;
this.b = b;
}
}
class Span extends Range {
constructor() {
super()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
- 即使没有出现 "use strict" 指令,class 声明体中的所有代码默认也处于严格模式。这意味着不能在类体中使用八进制整数字面量或 with 语句,而且忘记在声明之前使用变量也会导致语法错误。
- 与函数声明不同,类声明不会“提升”。函数定义就像是会被提升到包含文件或包含函数顶部一样,因此函数调用语句可以出现在函数定义之前。尽管类声明与函数声明有几分相似,但类声明不会被提升。换句话说,不能在声明类之前初始化它。
# 4、静态方法
class Range {
constructor() {}
static test() {
...
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# 5、委托
通过把相应操作委托给一个内部的对象来实现那些方法
class MyMap {
constructor() {
this.map = new Map();
}
get size() { return this.map.size; }
...
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 6、抽象类
class Atest {
has(x) {
throw new Error('Atest method')
}
}
class Btest extends Atest {
constructor() {
super();
}
has(x) {
// 实现 has 方法
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14