TOM
TOM

Reputation: 178

Class declarations and Class expressions in ES6

I'm not clear about Class expressions and Class declarations. Please help me to understand for the different between them.

Thanks

Upvotes: 3

Views: 3511

Answers (1)

m-a-r-c-e-l-i-n-o
m-a-r-c-e-l-i-n-o

Reputation: 2672

It's relatively simple.

In "Class Expressions", the class object NamedFoo is being assigned to a variable named Foo, like so:

var Foo = class NamedFoo {
  constructor() {}
  whoIsThere() {
    return NamedFoo.name;
  }
}

In "Class Declarations", the class object NamedFoo is being declared solely by itself, like so:

class NamedFoo {
  constructor() {}
  whoIsThere() {
    return NamedFoo.name;
  }
}

The distinction here also being that when it's a "Class Declaration", you can reference the class by using NamedFoo, however, when it's a "Class Expression", you'll only be able to reference the class by the variable that it was assigned to, in this case Foo.

I hope that helps!

Upvotes: 10

Related Questions