DEV Community

loading...
Cover image for Class and Constructor

Class and Constructor

Cathy Diaz
Full Stack Software Engineer
Updated on ・2 min read

Ohh man! Just when I thought I was getting the hang of Ruby, here comes another language to learn. JavaScript. I don't know if it's because of that reason that JavaScript seemed so hard to learn or simply because my brain could not grasp the new concepts. I choose to believe it's because I felt completely drained and needed a little break to recover.
anyways... sings "I'm back and I'm better" 🗣

for this project refactoring my code into a class and a constructor had me questioning my abilities. And isn't it so funny that 99.9% of the time it's something as small as a misspelled word? (I.did.not.do.that) :>

The first thing I did was to create a separate JS file. Since I will now be having two JS files, I went ahead and put them both in a source folder. Shown below.

SRC JS Files

The second thing I did was link my new JS file to my index.html file using a script tag. I also had to update my current script tag from <script src='index.js'></script> to <script src='src/index.js'></script>

so far, not so bad

Next in my new JS file I create a class Snack and inside that class a constructor.

class Snack

The constructor contains the initial data needed to create new instances on the snack class and because I used a constructor function, I will need to pair it with the new keyword which I included in my index.js file

New Keyword

If you are still confused on what classes and constructors do, this next paragraph really helped putting it into perspective.

What we really want to say is something like "Hey, constructor function, when you run, create a new copy of yourself, leaving the original unchanged and on that particular copy, set the properties based on the arguments passed into the function. The keyword new tells the constructor function to do exactly that.

The this keyword is used to reference the instance created.

Lastly, I created a render card that would show the attributes included in the constructor with the updated user input information.
For today, that is all.

HAPPY CODING

Discussion (0)