3

background

1.class should be defined in advance

I know there is no error because class is defined in advance.

class Polygon {
  log() { console.log('i am polygon'); }
}
const p = new Polygon();  // no error as I had expected.
p.log();

2.class is not hoisted

I also know the reason of this error. class is not hoisted, so this error is my expected result.

const b = new Bolygon();  // Uncaught TypeError as I had expected.
b.log();
class Bolygon {
  log() { console.log('i am bolygon'); }
}

question

In some case, such as this code(playground link), will class be hoisted?

I can't understand why new Hero() doesn't cause error in below. class Hero is hoisted?

class AppComponent {
  hero = new Hero('foo') // why no error?
}
class Hero {
  constructor(public name: string){}
}
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
onion mk2
  • 311
  • 2
  • 11
  • 1
    Technically, classes are hoisted, but not initialized, similar to `var`s - http://stackoverflow.com/a/35537963/43848 – artem Jan 05 '17 at 17:33

1 Answers1

6

The reason is that this line:

hero = new Hero('foo')

Is only evaluated when you instantiate AppComponent which is after the class Hero has been evaluated.
However, in your 2nd code snippet this line:

const b = new Bolygon();

Is evaluated first, before the class itself has been evaluated.

If you make AppComponent.hero static it will cause an error:

class AppComponent {
  static hero = new Hero('foo') // errro: Hero is not a constructor
}
Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299