In the code I am using a named class "Car". Now if I try to use like var carNew = new Car("ferrari");
, then it's throwing me an error. So what is the use of named class expression in ES6?
'use strict';
var car = class Car{
constructor(model){
this.model = model;
}
}
var carNew = new car("ferrari");
console.log(carNew); //car {model: "ferrari"}
console.log(carNew.constructor == car); //true
In case of class expressions you can use class name internally, but not outside of the class:
const Foo = class Self {
static greetingPrefix() {
return 'Hello, ';
}
greeting() {
return Self.greetingPrefix() + 'World';
}
};
const foo = new Foo();
console.log(foo.greeting()); // "Hello, World"
console.log(Self); // throws "Uncaught ReferenceError: Self is not defined"
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With