What is a constructor and other questions

Tell us what’s happening:
Hi, I solved the exercise by looking at the example but I didn’t understand it. I wrote my questions inside the code. Thank you!

Your code so far


// Only change code below this line
class Vegetable{
constructor(name){ //what is constructor and what it's doing here?
  this.name = name; //what is "this"? why do I need to define name = name?//
}
}
// Only change code above this line

const carrot = new Vegetable('carrot');
console.log(carrot.name); // Should display 'carrot'

Your browser information:

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

Challenge: Use class Syntax to Define a Constructor Function

Link to the challenge:

Unfortunately, the ES6 section introduces the concept of the constructor without explaining much about it. The following challenges are located in the Object Oriented Programming section which do give more information about what a constructor function is.

It might help to skip this particular set of challenges on the Class syntax for now and return once you have gone through the challenges listed above.

2 Likes

Edit: apologizes the email answer didnt go very well XD

There is also a few things that could be interesting to mention.

  • constructor(){ } is a function. And is an exact analogous of what you would write inside a constructor Function:
function Question(name){
this.name = name;
this.sayMe = ( ) =>console.log(this.name)
}

//instantiation
let Q1 = new Question("What is a constructor?")

class QuestionClass{
//class' body
constructor(name){
this.name= name;
this.sayMe = ( ) =>console.log(this.name
}
// class body ends. 
}
//instantiation
let Q2 = new QuestionClass("What is a constructor?")

So here constructor(params) = Question(params)

  • The keyword this is defined when you instantiate the class or the constructor function, and takes the value of the current object.
    (it’s much more complex but enough to start.)
1 Like