我知道没有错误,因为课程是事先定义的。
class Polygon {
log() { console.log('i am polygon'); }
}
const p = new Polygon(); // no error as I had expected.
p.log();
我也知道这个错误的原因。 class没有被提升,所以这个错误是我预期的结果。
const b = new Bolygon(); // Uncaught TypeError as I had expected.
b.log();
class Bolygon {
log() { console.log('i am bolygon'); }
}
在某些情况下,例如this code(playground link),会提升课程吗?
我无法理解为什么new Hero()
在下面不会导致错误。
class Hero
被悬挂?
class AppComponent {
hero = new Hero('foo') // why no error?
}
class Hero {
constructor(public name: string){}
}
答案 0 :(得分:4)
原因是这一行:
hero = new Hero('foo')
仅在实例化AppComponent
时评估了课程Hero
之后的评估。
但是,在您的第二个代码段中,这一行:
const b = new Bolygon();
在评估类本身之前首先进行评估。
如果您使AppComponent.hero
静态,则会导致错误:
class AppComponent {
static hero = new Hero('foo') // errro: Hero is not a constructor
}