Use class Syntax to Define a Constructor Function // console.log(carrot.name) = carrot?

Use class Syntax to Define a Constructor Function // console.log(carrot.name) = carrot?
0

#1

Hello!

I have a question about the “console.log(carrot.name)”.
As I understand, object contains info like this -> Object { name: “carrot”}
Why the result of “console.log(carrot.name)” become “carrot”??
I cannot understand.

Please help me! :slight_smile:

function makeClass() {
  "use strict";
  class Vegetable {
    constructor (name) {
      this.name = name;
    }
  }
  return Vegetable;
}
const Vegetable = makeClass();
const carrot = new Vegetable('carrot');
console.log(carrot.name);

#2

These lines are what help assign the “carrot” to the carrot.name. constructor makes sure that any variable that is created with the Vegetable class takes the first argument, name, and assign it to the instance’s name variable.

If are confused, feel free to ask more!


#3

When you write new Vegetable(‘carrot’) it returns a function with ‘carrot’ being passed into the Vegetable class’s constructor function. The constructor function takes a name argument and assigns it to this.name, which allows the created function to have a name property with the value of what was passed into it (in this case ‘carrot’).

If I wrote the following code and used the makeClass function as written above. I would still be passing in ‘carrot’ to become the value of the corn function’s name property.

const Vegetable = makeClass();
const corn = new Vegetable('carrot');
console.log(corn.name); // still displays 'carrot'