Constructors
You can create reusable objects in more than one way, so let's explore another popular pattern for creating them called the constructor.
New Keyword
let Dog = function() {
let name;
}
let firstDog = new Dog;
firstDog.name = "Mojo"
secondDog.name = "Pugsley"
console.log(firstDog) //{"name":"Mojo"}
console.log(SecondDog) //{"name":"Pugsley"}
Constructors are a way to write classes with JavaScript functions. JavaScript Classes never really took off, but you still see this type of pattern in a lot of places...and think there's some merit to them.
Some things about this code. I used a capital letter for the name of the function. That's common when creating this pattern that acts like a class.
There's also a keyword we hadn't seen before called new. That creates an instance of the object. Each instance has it's own set of properties.
The Prototype
let Dog = function() {
let name;
}
Dog.prototype = {
speak: function(what) {
return (console.log(what));
}
}
let firstDog = new Dog;
firstDog.name = "Mojo"
firstDog.speak('woof')
JavaScript objects have a special property called the prototype. If you've visited online documentation, you may have seen this keyword.
This feature allows all objects to be extended. When we create our Dog class, we can target the prototype and add any number of features to that class. In this case, we're adding a speak function.
Separate Function
let speak = function(what) {
return (console.log(what));
}
let Dog = function() {
let name;
}
Dog.prototype.speak = speak
let myDog = new Dog;
myDog.name = "Mojo"
myDog.speak('woof')
We can also write the function externally. That way we could add this same functionality to another object.
Let's try to write another function that creates a cat and adds the same speech functionality.
The prototype is a great way to expand an existing function...since every object has a prototype you can redefine just about every way JavaScript works.