1、class 会被优先加入词法环境,但不会初始化赋值。执行Foo类之前使用Foo进入暂时性死区,类似let、const声明变量。
const bar = new Bar(); // ok
function Bar(){
this.bar = 42;
}
const foo = new Foo() // ReferenceError: foo is not defined
class Foo {
constructor(){
this.foo = 42;
}
}
2、class 声明内部会启用严格模式
// 引用一个未声明的变量
function Bar(){
baz = 42; // ok
}
class Foo {
construtor(){
fol = 42; // ReferenceError: fol is not defined
}
}
3、class 的所有方法(包括静态方法和实例方法)都是不可枚举的。
// 引用一个未声明的变量
function Bar() {
this.bar = 42;
}
Bar.answer = function() {
return 42;
};
Bar.prototype.print = function() {
console.log(this.bar);
};
const barKeys = Object.keys(Bar); // ['answer']
const barProtoKeys = Object.keys(Bar.prototype); // ['print']
class Foo {
constructor() {
this.foo = 42;
}
static answer() {
return 42;
}
print() {
console.log(this.foo);
}
}
const fooKeys = Object.keys(Foo); // []
const fooProtoKeys = Object.keys(Foo.prototype); // []
4、calss 所有方法(包括静态方法和实例方法)都没有原型对象prototype,所以也没有[[construct]],不能使用new来调用。
class tiger{
say(){
console.log("ao")
}
}
const fooPrint = new tiger.say() //TypeError: foo.print is not a construtor
5、必须使用new调用class。
function Bar(){
this.bar = 42;
}
const bar = Bar(); // ok
class Foo {
constructor() {
this.foo = 42;
}
}
const foo = Foo(); // TypeError: class construtor Foo cannt be invoked without 'new'
6、class 内部无法重写类名。
function Bar() {
Bar = 'Baz' // ok
this.bar = 42;
}
const bar = new Bar();
class Foo {
construtor() {
this.foo = 42;
Foo = 'Fol'; // SyntaxError: Identifier 'Foo' has already been declared
}
}
const foo = new Foo();
结语: 谢谢