Table of Contents
Lastly, we practiced creating object, got familiar with „this“ keyword and also got better with accessing methods and properties of objects. All of this will be very useful today. What’s on program? We will take a look at another way to create objects constructors that can be used to create instances of objects later. Stop talking, start coding. Let’s dive in …
Recently we talked about two ways to create objects in JavaScript. First was object constructor and second was object literal. However, there is one another option we didn’t touch yet. This option can be pretty useful when you want to create couple of instances that will differ only in small detail. For example, you want to create five car objects. All of them will have four wheels, be new and they all will be electric. The only thing that will be different will be the brand. To get this done, you can create the first one and then copy and paste the code for four times.
Prototype
This is very a dumb approach. Instead, you can create your own object “prototype”. This is something like a “default” object constructor function which will take brand as a parameter and the rest of properties will set with specific value. After this, you can create new instance of this object by declaring new variable followed by equal sign, “new” keyword and name of the function (with parameter in parenthesis).
JavaScript:
// Creating our customized object “constructor” function Car(brand) { // remember to end every line EXCEPT the last one end with comma this.brand = brand, this.numOfWheels = 4, this.condition = “new”, this.type = “electric”, this.honk = function() { console.log(“Honk, honk!”); } } // creating five instances of car object var tesla = new Car(“Tesla”); var mazda = new Car(“Mazda”); var bmw = new Car(“BMW”); var lamborghiny = new Car(“Lamborghiny”); var ford = new Car(“Ford”);
See? This is much easier, faster and also more intelligent approach. You can declare “Car” function with lower c – function car(brand) – and it will work exactly same (remember to use “new car()“ for creating new instance). However, it is best practice to write the first letter as capital. It will help you to differentiate between the regular function and objects later. What’s more, “new Car()” looks more like default “new Object()”.
All of the variables declared above share numOfWheels, condition and type properties and also honk method. To test it, we can access these properties and method through individual car instances and let their values be printed into the console. To do that we will again use “dot” notation.
JavaScript:
// Accessing properties (dot notation) console.log(tesla.brand); // result - “Tesla” console.log(tesla.condition); // result - “new” console.log(mazda.brand); // result - “Mazda” console.log(mazda.type); // result - “electric” console.log(bmw.numOfWheels); // result - 4 // since honk() function prints to the console as default, we will not use console.log() method bmw.honk(); // result - “Honk, honk!”
You can also use a little trick for cases if user of the program will not provide the parameter for brand when using “Car” constructor function. We will need to add “||” operator (or) to “this.brand” line inside the “Car” right after the “brand”. This operator will be followed by “backup” value. It looks like this:
JavaScript:
function Car(brand) { // our little trick with “||” operator this.brand = brand || “Who knows”, this.numOfWheels = 4, this.condition = “new”, this.type = “electric”, this.honk = function() { console.log(“Honk, honk!”); } } // creating new car instance without parameter var car1 = new Car(); console.log(car1.brand); // result - “Who knows”
Voila, the problem with users not paying attention is solved. How does it work? The “||” (or) operator says JavaScript to use brand parameter, if provided, or to use “Who knows” otherwise. Remember that order is very important. If you switch the values – “this.brand = “Who knows” || brand” – “Who knows” string will be used as default, so even if you use parameter all cars will print out this string.
One more example on this “customized” constructor. Let’s create object “Human” with following properties – numOfHands, numOfLegs, living, age, sex, name – and method speak. This constructor will take name, age and sex as parameters, the rest will be shared.
JavaScript:
function Human(name, age, sex) { this.name = name, this.age = age, this.sex = sex, this.numOfHands = 2, this.numOfLegs = 2, this.speak = function() { // in functions is more common to use “return” command – this does NOT prints data into console return “Hi, my name is ” + this.name + “, my age is ” + this.age + “ and I am ” + this.sex + “.”; } } var man1 = new Human(“Thomas”, 31, “male”); var woman1 = new Human(“Alice”, 28, “female”); var man2 = new Human(“Jeffrey”, 15, “male”); var woman2 = new Human(“Kimberly”, 89, “female”); console.log(man1.name); // result - “Thomas” console.log(man1.sex); // result - “male” console.log(woman1.name); // result - “Alice” console.log(woman1.sex); // result - “female” console.log(man2.age); // result – 15 // Since “return” does not prints out the data to console, we have to use console.log() console.log(man2.speak()); // result - “Hi, my name is Jeffrey, my age is 15 and I am male.” console.log(woman2.age); // result - 89 console.log(woman2.speak()); // result - “Hi, my name is Kimberly, my age is 89 and I am female.”
Inheritance
These “customized” object constructors are just awesome! Right? They allow you to save a huge amount of time and to avoid unnecessary repetition. However, there is one more ability we didn’t talk about yet. Wait for it … You can actually add more properties and methods to object prototype created earlier by using “dot” notation and “prototype” keyword. When you add more properties, all previously created instances will inherit these properties or methods. This is called “inheritance” – if you change the prototype all of its instances will change too. However, if you change the instance, prototype stay same. The syntax is name of object prototype followed by dot, “prototype” keyword, dot , name of new property or method, equal sign and value. Let’s modify our Human object prototype to see how it works.
JavaScript:
// create Human prototype function Human(name, sex) { this.name = name, this.sex = sex, this.speak = function() { // in functions is more common to use “return” command – this does NOT prints data into console return “Hi, my name is ” + this.name + “ and I am ” + this.sex + “.”; } } var man1 = new Human(“Josh”); var woman1 = new Human(“Elizabeth”); // testing the functionality console.log(man1.name); // result - “Josh” console.log(woman1.name); // result - “Elizabeth” // adding age property to Human prototype Human.prototype.numOfHands = 2; Human.prototype.numOfLegs = 2; Human.prototype.living = true; // testing new property on existing object instances of Human console.log(man1.numOfHands); // result – 2 console.log(woma1.numOfLegs); // result – 2 console.log(man1.living); // result – true
Inheritance and prototypes are very important topics in any OOP language (Object Oriented Programming). When you understand what these things are and how they work, it will move your skills of programming, imagination, knowledge and problem-solving skill to brand-new level. You will see, how individual instances are connected with their prototypes and how one change can impact other objects. It is like the material world around us.
Before we close it, there is one more thing you can do with prototypes. You can create two prototypes and let one of them inherit the properties and methods of the second. Let’s take a look at simple example. We will create “Human” prototype with numOfHands, numOfLegs and living properties. After that, we will create another prototype called “Male” with name and sex properties and speak method. Prototype “Male” will take one parameter – name.
JavaScript:
// creating Human prototype function Human() { this.numOfHands = 2, this.numOfLegs = 2, this.living = true } // creating “Male” prototype function Male(name) { this.name = name, this.sex = "male", this.speak = function() { return “Hi, my name is “ + this.name + “.”; } };
Now will use “prototype” keyword to connect “Male” prototype with “Human” prototype. When we do this, “Male” prototype will contain all properties declared inside “Human” prototype – it will inherit them. However, “Male” prototype will remain independent.
JavaScript:
// connecting “Male” to “Human” Male.prototype = new Human(); // creating new instance of Male var man2 = new Male(“Alex”); // testing properties console.log(man2.name); // result – “Alex” console.log(man2.numOfHands); // result – 2 console.log(man2.sex); // result – “male” console.log(man2.living); // result – true
Summary
With this, we finished whole tutorial on objects. Now you are fully equipped to create and manage any data type available. The best thing to do now is to return and refresh all we talked about, you will need it. In future post we will take a look at loops and conditional statements. If you have some gaps in any part or don’t understand all topics, you can go through trial and error, leave a comment or send me a message on some of the social networks. Remember, I’m here to help you.
If you liked this article, please subscribe so you don't miss any future post.
If you'd like to support me and this blog, you can become a patron, or you can buy me a coffee 🙂