How does class creation work?

Tell us what’s happening:

Okay, I solved this challenge but I don’t really understand how it works.

What are these three lines doing?

const Vegetable = makeClass();
(^ Is this somehow creating a class? I thought that was what the below line was doing.)
const carrot = new Vegetable('carrot');
(^This one confuses me a bunch.)

console.log(carrot.name)
(^ So now carrot an object?)

Your code so far


function makeClass() {
  "use strict";
  /* Alter code below this line */

    class Vegetable {
      constructor(name){
        this.name = name;
      }
    }
  /* Alter code above this line */
  return Vegetable;
}
const Vegetable = makeClass();
const carrot = new Vegetable('carrot');
console.log(carrot.name); // => should be 'carrot'

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function

makeClass is a function that returns a class definition. So executing makeClass gives you that class definition. So that whole thing is exactly the same as just writing class Vegetable { ...., then later on the same const carrot = new Vegetable(....

It is wrapped in that function for the benefit of the tests, to allow that `“use strict” statement to be there. It is confusing – it isn’t there as an example of what you need to do, only the bit inside the “Alter code below/above” is actually relevant – and is being removed once the next version of FCC gets pushed out.

also

Classes are used to create objects, so yup.

2 Likes