With the following code
var car = class Car{ /* ... */ }
var carNew = new Car("ferrari");
throws an error, why?
Car
has not entered the scope because you've written a class expression, similar to using function
in a function expression
var foo = function Bar() {};
foo; // defined
Bar; // undefined
var carNew = new car("ferrari");
works, why?
For the same reasoning as above, the car
identifier is defined in your scope and points to the class expression
What is use of named or unnamed class expression [...]?
Lets look back at function
again. So now think, if Bar
wasn't defined in the scope we were working in, where was it defined?
Well, obviously we have foo.name === 'Bar'
, but we could also do
var foo = function Bar() {console.log(Bar)};
foo(); // Bar logged, we see Bar === foo here
Great, so we can reference Bar
inside the function.
It is exactly the same with class
, we can reference Car
from within the class expression itself, letting us do recursive behaviours or copy static references to instances etc.
I've added such a reference to make it easy to see in the code below
var car = class Car {
constructor(model) {
this.model = model;
this.foo = Car; // the big C Car that was ReferenceErroring outside
}
};
var bar = new car();
console.log(bar.foo); // logs class Car (=== car)