class 声明会提升,但不会初始化赋值。Foo 进入暂时性死区,类似于 let、const 声明变量。
const bar =newBar();// it's okfunctionBar(){this.bar =42;}const foo =newFoo();// ReferenceError: Foo is not definedclassFoo{constructor(){this.foo =42;}}
class 声明内部会启用严格模式。
// 引用一个未声明的变量functionBar(){
baz =42;// it's ok}const bar =newBar();classFoo{constructor(){
fol =42;// ReferenceError: fol is not defined}}const foo =newFoo();
class 的所有方法(包括静态方法和实例方法)都没有原型对象 prototype,所以也没有[[construct]],不能使用 new 来调用。
functionBar(){this.bar =42;}
Bar.prototype.print=function(){
console.log(this.bar);};const bar =newBar();const barPrint =newbar.print();// it's okclassFoo{constructor(){this.foo =42;}print(){
console.log(this.foo);}}const foo =newFoo();const fooPrint =newfoo.print();// TypeError: foo.print is not a constructor
必须使用 new 调用 class。
functionBar(){this.bar =42;}const bar =Bar();// it's okclassFoo{constructor(){this.foo =42;}}const foo =Foo();// TypeError: Class constructor Foo cannot be invoked without 'new'
class 内部无法重写类名。
functionBar(){
Bar ='Baz';// it's okthis.bar =42;}const bar =newBar();// Bar: 'Baz'// bar: Bar {bar: 42} classFoo{constructor(){this.foo =42;
Foo ='Fol';// TypeError: Assignment to constant variable}}const foo =newFoo();
Foo ='Fol';// it's ok
子类可以直接通过 __proto__ 寻址到父类。
classSuper{}classSubextendsSuper{}const sub =newSub();
Sub.__proto__ === Super;