ES6: Class Syntax to Define a Constructor Function

Tell us what’s happening:

Your code so far


function makeClass() {
  "use strict";
  /* Alter code below this line */
  class Vegetable {
    constructor(Vegetable){
      this.Vegetable = Vegetable;
    }
  }
  /* Alter code above this line */
  return Vegetable;
}
const Vegetable = makeClass();
const carrot = new Vegetable('carrot');
console.log('carrot'); // => 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/73.0.3683.86 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

What’s the problem you’re having?

Ok, so the constructor is a function that lets you create an object. In that function, you can give the object properties by assigning them to property name, this.myProperty = someValue, where this represents the object you’re creating. So like

class Person {
  constructor (name) {
    this.name = name;
  }
}

The constructor is a function that takes one parameter (called name in the above) and creates a new object with one property (also called name), with the value you pass into the function.

new Person("Steve") creates an object of the type Person that looks like { name: "Steve" }.

So you have a constructor for an object of the type Vegetable that has a parameter called Vegetable that creates an object with one property, called Vegetable that has the value of whatever the parameter Vegetable is. Confusing.

Anyway, the property name is not supposed to be Vegetable, what it is supposed to be is in the last paragraph of the instructions.

1 Like

okay, so how would you write the actual code?

I can not print ‘carrot’

The property your putting into your Vegetable object is not supposed to be called Vegetable as well, what it is supposed to be is in the last paragraph of the instructions.

If the property was called Vegetable (as it is on your code), then if you did

const myVegetable = new Vegetable('carrot')

Then myVegetable would be an object like

{ Vegetable: 'carrot' }

And to get the name of the vegetable, you would have to do

myVegetable.Vegetable
1 Like