- Write methods that use instance data and parameter data
In review, with Object-Oriented programming (OOP), we can use classes to represent concepts such as students, books, comments, posts, or even animals.
We should only have to define the properties and methods of a class once.
Different instances of this class will all have the same properties and
methods. Specific values for those properties will be different between
instances. Mickey and Minnie are both Mouse instances that have a property
called name, but the value of that property for each is different.
With knowledge of constructors, we can use JavaScript's classes as a
template for instances.
To practice OOP concepts, let's create 3 classes that use constructor
methods. These constructors will assign properties based on initial parameters.
We'll also write methods that leverage these properties.
- Create
classesCat,Dog, andBird - Each of these
classes will accept the parametersnameandsexand will store those values as properties.
class Cat {
//...
}
class Dog {
//...
}
class Bird {
//...
}For each class, create the method speak.
- For an instance of
Cat, speak returns "namesays meow!", - For an instance of
Dog, speak returns "namesays woof!" - For an instance of
Bird, speak returns conditional output. If the instance ofBirdismale, speak returns "It's me!name, the parrot!". If it is notmale, speak returns "namesays squawk!".
We've learned to instantiate class instances, or "objects" in JavaScript. The constructor function allows us to easily define and standardize the instances we create. Good work!