Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is use of named or unnamed class expression in ES6?

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
like image 204
nihar jyoti sarma Avatar asked Jan 02 '16 11:01

nihar jyoti sarma


2 Answers

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"
like image 77
alexpods Avatar answered Oct 03 '22 23:10

alexpods


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)
like image 28
Paul S. Avatar answered Oct 04 '22 00:10

Paul S.