class
声明会提升,但是不会被初始化赋值,所以优先初始化赋值,则会进入 暂时性死区
,类似let
,const
变量
const bar = new Bar(); // ok
function Bar() {this.bar = 42;}
const foo = new Foo() // Foo is not defined
class Foo{constructor() {this.foo = 42;}
}
class
内部启动 严格模式
function Bar(){baz = 42; // OK}
const bar = new Bar();
class Foo {constructor() {foo = 42; // foo is not defined}
}
const foo = new Foo();
class
的所有方法(包括静态方法和示例方法)都没有原型对象 portotype,所以也没有 [[construct]],不能使用new
来调用
function Bar() {this.bar = 42;}
Bar.prototype.print = function (){console.log(this.bar)
}
const bar = new Bar();
cont barPrint = new bar.print() ; // 42
class Foo {constructor() {this.foo = 42;}
print () {console.log(this.foo)
}
}
const foo = new Foo();
const fooPrint = new foo.print(); // foo.print is not a constructor
必须使用 new
来调用class
function Bar() {this.bar = 42;}
const bar = Bar() ; // bar.bar: 42
class Foo() {constructor () {this.foo = 42;}
}
const foo = Foo() // Class constructor Foo cannot be invoked widhout 'new'
class
内部无法重写类名
function Bar() {
Bar = 'Baz' ;
this.bar = 42;
}
const bar = new Bar();
Bar // 'Baz'
bar.bar // 42
class Foo{constructor() {
this.foo = 12;
Foo = 'Fol' ; // err:Assignment to constant variable
}
}
const foo = new Foo();
Foo = 'Fol'; //