Exploring Class Definitions
Certain Rules to Comply With
Ensuring that the class is defined in advance helps avoid errors.
class Polygon {
log() { console.log('i am polygon'); }
}
const p = new Polygon(); // Expected: no errors
p.log();
Understanding Hoisting of Classes
Knowing that classes are not hoisted explains this error outcome.
const b = new Bolygon(); // Expected: Uncaught TypeError
b.log();
class Bolygon {
log() { console.log('i am bolygon'); }
}
Questioning Class Hoisting
In situations like this code(playground link), will the class be hoisted?
The confusion arises when new Hero()
does not trigger an error as seen below.
Is class Hero
being hoisted?
class AppComponent {
hero = new Hero('foo') // Why is there no error?
}
class Hero {
constructor(public name: string){}
}