Coding in JS - Lesson 3
by onejdc
HTML
<h1 class='center'>Lesson 3 - Javascript Classes</h1>
CSS
html, body { margin: 0; padding: 0; background-color:black;color: rgb(0,228,150)}
h1 { display:block; ;text-align:center;}
.center { display:flex;justify-content:center;align-items:center; height:90vh;}
JavaScript
//======================================================================
// Introduction to Javascript, Part 3
//======================================================================
/*
Recall that in Part 2, we covered the following topics:
- Arrays
- Objects
- Object Functions, aka METHODS
- Object properties
*/
/*
I mentioned that simply writing our objects as key/value pairs was the
naive approach. That's because an object can also have a full defintion
behind it, called a CLASS.
A CLASS has lots of features that make objects much more powerful:
- You can make multiple copies of an object, each with different
property values
- You can add validation to property values to enforce data rules
- You can add functions to objects (METHODS).
- a CLASS can be specific, and INHERIT parts from more generic
CLASSes.
*/
//--------------------------------------------------------------------
// Classes
//--------------------------------------------------------------------
/*
Let's say you're building a single-player Simulator game, of kids going
to school. The player controls one of the students, but you need to add
lots of other NPC (non-playable character, i.e. computer-controlled)
students. These students all need different characteristics, and need to be
able to do things independently of each other.
Manually creating a bunch of objects for this task would be pretty tedious.
Not only that, but if you needed to add a feature to an NPC, going through
every object would be a pain. A good solution here is a combination of loops
and the thing we're going to study now -- a CLASS.
*/
// classes are created with the 'class' keyword. the name of the class should be
// capitalized
class Student {
// these are properties for the objects we create.
// we can give them default values.
grade;
age;
name;
ridesTheBus = true;
location;
// when an object of this class is created with the 'new' keyword,
// the 'constructor'...