Skip to main content
2. Advanced CSS and Intro JavaScript
2. Advanced CSS and Intro JavaScript
JavaScript IV introduces you to the powerful paradigm of Object Oriented Programming (OOP) in JavaScript. We will take a deep dive into these topics:
- The JavaScript Prototype object
- constructor functions
- Pseudo-classical Inheritence
- the
classkeyword
By the end of the day you should be familiar with objects and how to use Constructors and Classes to build out objects and achieve inheritance across these objects.
At the end of this module, you should be able to:
- describe and demonstrate how class syntax works
- convert a pseudo classically instantiated program into class syntax
Accept criticism gracefully and learn from it. Criticism is valuable for growth and development. When you ask for a opinion in a professional setting, the chances of the person is trying to hurt your feeling, or make you feel small or be actively cruel is so vanishingly small that, despite occasions where others are factually wrong with their criticism, you should hold onto it like a precious gift.
Review each preclass resource before class.
-
Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
-
Try watching this video on www.youtube.com, or enable JavaScript if it is disabled in your browser.
Because the original prototype system in JavaScript is rather clunky, and because there are multiple ways to skin a cat (achieve inheritance), we now have the class keyword to simplify our lives significantly. With the introduction of the class keyword however, we gain a lot of abstraction, which is why it is extremely important for you have seen how to achieve inheritance with what is known as the psuedo-classical inheritance pattern.
Once you are familiar with how the prototype works, how inheritance is achieved through the psuedo-classical pattern and how to implement constructor functions, you’re going to LOVE how easy it is to do this with the class keyword.
With ES6 we gained the ability to use what is known as the class keyword. The class keyword is what we call “syntactic sugar” on top of the object built into JavaScript and the object’s prototype system. The class keyword is not a new way of achieving object-oriented inheritance in JavaScript.
You already know how to work with classes because you know all about constructor functions and the Object prototype. Working with constructor functions to achieve object creation in JavaScript is fundamental to understanding how classes work. Remember that classes in JavaScript are just special functions.
There are two types of ways we can work with and define classes (much like functions how there are multiple ways of declaring/defining functions) class expressions & class declarations. The pattern we learn today will be called class declarations.
Let us begin by observing some syntax:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
} *
Here we have declared a Rectangle class. It looks pretty similar to the constructor functions that we’re used to; however, this time, we’re deliberate about placing it inside of the class. You can think of the constructor function as the foundation of every class. When present, you’ll be building your object’s properties (these get returned when you call new) inside the constructor’s body on the this keyword.
Any properties you bound to your created object can be passed in through the constructor method. In this case, we have height & width as attributes that we’d like to store on our created object. Remember: classes will return us objects.
Now, if I wanted to use this class to create an object, it would look very much the same as constructor functions. All I have to do is declare some variable and assign it to the class by using the new keyword.
Let us declare a new Rectangle and log the result.
const newRect = new Rectangle(400, 800);
console.log(newRect);
Logs out:
Rectangle { height: 400, width: 800 }
Inheritance is where classes shine. The extends keyword, and super(); function make it trivial to bind our classes together to achieve some simple object inheritance. The extends keyword will abstract away any of the Class.call syntax that we’re used to. super() tells a parent’s constructor to be concerned with the child’s attributes and abstracts away the Object.create(this, Class) syntax that is trickier to understand.
Here’s how Object inheritance works with classes:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' makes a noise.');
}
}
Notice that speak() is a method with some special syntax in this class. This method will not be a method on the object, but it will live on the object’s prototype instead, which is nifty when you’re worried about memory and such.
If I wanted to create a sub-class from our Animal class, it’s effortless.
class Dog extends Animal {
constructor(name) {
super(name);
}
speak() {
console.log(this.name + ' barks.');
}
}
Isn’t that so much nicer? No more .bind(), .call(), .apply() and Object.create() etc. We simply just understand the little nuances and it works.
And using this child class:
const doggy = new Dog('Grizzly');
doggy.speak();
---> 'Grizzly barks.'
This is an example derived directly from the MDN documentation. So once you’re done learning from here, you can head over there and check this out.
Now follow along with me as we build out some quick classes.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} says, Hello!`);
}
}
Animal is going to be our base class. All other classes will inherit from Animal. So lets define a couple of different animals:
class Dog extends Animal {
constructor(name) {
super(name);
}
speak() {
console.log(`${this.name} barks!`);
}
}
class Cat extends Animal {
constructor(name) {
super(name);
}
speak() {
console.log(`${this.name} Meows!`);
}
}
And if we want to use them:
const bowWow = new Dog('Grizzly');
const kitty = new Cat('Fluffertons');
console.log(bowWow);
console.log(kitty);
bowWow.speak();
kitty.speak();
Check it out! If you didn’t find this astounding, you will once we convert the constructor functions we’ve built over to use the class keyword!
For this challenge, we want you to build out a few classes based on your ancestral tree. (If you’re not sure about any of your family’s information go ahead and make up names like “Grandpa” and “Grandma”).
Go back a few generations and create a Grandpa or Grandma class. Name either one for your parent’s parents.
Create a Parent class named for one of your parents. Parent inherits from Grandpa/Grandma.
Create a Child class (you) who inherits from Parent.
Be sure to log out any methods that you use for this project. Any features (i.e. eye color, hair color) that you’d inherit from your ancestors, be sure to include as attributes and pass them down the class chain. Every class should at least be instantiated with the following attributes. name, birthPlace, eyeColor, hairColor.
Now that you have had some experience writing constructor functions to create new objects that inherit from each other, it’s time to convert those pseudo classically instantiated programs into class syntax.
Now that we have had plenty of practice with pseudo-classical inheritance. We’ll take the time to convert our beautiful little Person constructor.
Some critical notes on classes:
- The
objectour class returns will have attributes assigned to it from theconstructor()function. - All methods attached to the class body will be stored on the
Objectsprototype in a special way. There is a bit more magic here than justObject.create(Foo.prototype);andClass.call(this, attrs);But now that we know this, we can accept that the class keyword does this gloriously for us. - The ‘extends’ keyword is used to
extenda parent object. A clue to finding out if a class is asub-classis to look for extends. - Finally, if you’re going to use
extend,super()needs to be called from within the constructor function. This is to pass any new attributes back up to the constructor of the parent object.
Examples found below as we refactor our code from the previous objective:
function Person(attributes) {
this.age = attributes.age;
this.name = attributes.name;
this.homeTown = attributes.homeTown;
}
Person.prototype.speak = function () {
return `Hello, my name is ${this.name}`;
};
class Person {
constructor(attributes) {
this.age = attributes.age;
this.name = attributes.name;
this.homeTown = attributes.homeTown;
}
speak() {
return `Hello, my name is ${this.name}`;
}
}
Let’s review:
speakis now assigned to the object’s prototype. (open the console and show this off after you instantiate an object.)thisis a single class, meaning it is notextendinga parent class. We’ll get toextends soon.- The code is clean now! Instead of having to reference the object’s prototype over and over to create methods on it, you can just add them to the class body. This is how we use classes today. You’ll get plenty of time to use this when we get to React. React uses classes all the time.
Classes come in handy when we have children objects that will be sub-classes of their parents. We accomplished this in the previous module with Child (see below).
function Child(childAttrs) {
Person.call(this, childAttrs); // this is the special sauce
this.isChild = childAttrs.isChild; // this will be a special attribute to Child
}
Child.prototype.checkIfChild = function() {
if(this.isChild) {
console.log(`${this.speak} and I am a child object`);
}
};
With classes, we can rewrite that function like this:
class Child extends Parent {
constructor(childAttrs) {
super(childAttrs);
this.isChild = childAttrs.isChild;
}
checkIfChild() {
if(this.isChild) {
console.log(`${this.speak} and I am a child object`);
}
}
Now we’re going to make fred and pebble into objects and see what they look like! Be ready to be blown away!
const fred = new Person({
age: 35,
name: 'Fred',
homeTown: 'Bedrock'
});
const pebbles = new Child({
age: 3,
name: 'Pebbles',
homeTown: 'Bedrock',
});
For this assignment, we’re going to be converting your Fruit constructors so that they can leverage the power of the class keyword.
Following along here with the recorded video above will help us all understand this stuff a lot more.
Convert constructor functions into class syntax using class, extends, and super() here.
-
This challenge focuses on classes in JavaScript using the new class keyword.
You can use class recordings to help you master the material.
-
Classes for WebPT22 w/Nathan Braun
JavaScript IV introduces you to the powerful paradigm of Object Oriented Programming (OOP) in JavaScript. We will take a deep dive into these topics: The JavaScript Prototype object constructor functions Pseudo-classical Inheritence the class keyword By the end of the day you should be familiar with objects and how to use Constructors and Classes to build out objects and achieve inheritance across these objects.
To demonstrate mastery of this module, you need to complete and pass a code review on each of the following:
-
Objective challenge:
For this challenge, we want you to build out a few classes based on your ancestral tree. (If you’re not sure about any of your family’s information go ahead and make up names like “Grandpa” and “Grandma”).
Go back a few generations and create a
Grandpa or Grandmaclass. Name either one for your parent’s parents.Create a
Parentclass named for one of your parents.Parent inherits from Grandpa/Grandma.Create a
Childclass (you) who inherits fromParent.Be sure to log out any methods that you use for this project. Any features (i.e. eye color, hair color) that you’d inherit from your ancestors, be sure to include as attributes and pass them down the class chain. Every class should at least be instantiated with the following attributes.
name, birthPlace, eyeColor, hairColor. -
Objective challenge:
Convert constructor functions into class syntax using
class,extends, andsuper()here. -
Project: Classes Project