new Class vs new Function

编译前

1
2
3
4
5
6
7
8
9
10
11
12
13
function a () {
console.dir("Funciton a")
}

class A {
constructor() {
console.dir('class A')
}
}

new a();

new A();

编译后

es5
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
"use strict";

function _instanceof(left, right) {
if (
right != null &&
typeof Symbol !== "undefined" &&
right[Symbol.hasInstance]
) {
return !!right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
}

function _classCallCheck(instance, Constructor) {
if (!_instanceof(instance, Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}

function a() {
console.dir("Funciton a");
}

var A = function A() {
_classCallCheck(this, A);

console.dir("class A");
};

new a();
new A();

_classCallCheck

  1. 作用: 防止Class A被当成函数调用A();

Symbol.hasInstance

  1. 作用: 用户可以用来自定义instaceof, 判断对象是不是构造器的实例。

  2. 兼容性 IE不支持

  3. 实现instanceof

example:

1
2
3
4
5
6
7
class MyArray {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}

console.dir([] instanceof MyArray); // true;