5. JS Objects basics Public

5. JS Objects basics

Kostas Diakogiannis
Course by Kostas Diakogiannis, updated more than 1 year ago Contributors

Description

Introduction to javaScript objects

Module Information

No tags specified

Context

Course's Objectives 1. The learner understands how to store multiple values and multiple variables into a single data type. 2. The learner knows how to create his/her own objects and store information there. 3. The learner knows what properties and methods that belong to an object are. 4. The learner understands the 'this' and 'new' keywords. 5. The learner knows how shared info is being used through object inheritance. 6.The learner knows how to iterate through loop properties and have access to all objects info.
Show less
No tags specified

Context

Creating JS Objects Objects are one of the 7 standard JS Data types and are heavily used to store multiple variables together. Objects are comprised from a set of key value pairs (syntax-wise like CSS). The key acts like a placeholder and the value is as usually the value this variable contains. In the example above we have created an object to store information in one place, where otherwise we would have needed multiple variables. This object now holds information about a person. The pieces of information are the keys (or object's properties) and the values can be any JS data type (even other objects as we will see later on). In order to access a specific piece of info now we need to console.log(jake.firstName) etc.
Show less
No tags specified

Context

Accessing Object properties As is shown above there are 2 ways to gain access to an object's property. The . (or dot way) and the [' '] (brackets way). Bear in mind that there is no difference between the two methods. This is only syntactic sugar, although when accessing by brackets we need to put the wanted property inside quotes as a string.
Show less
No tags specified

Context

Object's methods and the 'this' keyword. Methods are functions that belong to an object and they modify it's properties. What object properties are to variables, methods is to functions also.  This is possible through the 'this' javaScript keyword that points to  the execution context. Take a look at the example above. When the object is created the profession of the person is 'Machine Learning engineer'. This person though has a method attached that can change this property. The changeProfession method.  This method whenever is called, takes a single string argument, and put it as a new value to the profession property of this! But what does this mean? This is a reference to WHATEVER calls the changeProfession function. In our case the changeProfession is a method that belongs to the jake object, that's why we call it as jake.changeProfession. That means that the whole environment the changeProfession function lives and breathes is inside the jake object. This is a reference to the context of the function (the jake object in this case). Notice: The point of reference of this keyword can change through a specific method later, if no object is provided and a function is global, the this keyword refers to the global (or window) object. Example: Imagine you wake up happy one day and you decide to let anyone know about it. You go outside of your apartment and you scream 'I love this country'. Which country do the people that surround you think that you are talking about. Since you havn't really named the country it could be any country, right? But since you are in Germany everyone will automatically assume that you are talking about Germany. Why? Because you are in Germany the time the action happens. It surrounds you, is your environment, or your context better. If you were in France then 'this country' would mean France etc.
Show less
No tags specified

Context

O-1 Create your first object Create an object about a person that lives in your country for some years (unknown how many, you define it) and holds the information below. Firstname, lastname, age, years of residence in your country, his own nationality, current profession and current salary.  Then create a method that changes it's nationality to your country's nationality if the years of residence is greater or equal to 7.
Show less
No tags specified

Context

O-2 Convert currency Create three objects for three people with the following info. Firstname, lastname, bank account (a number in us dollars) and country of residence.  The bank account is going to be a number that the person has to his/her bank account in US dollars.  Add a new property that corresponds to how much 1$ to the currency of every person's country corresponds. The persons are coming from Greece, Switzerland and Australia respectively.  Create a function that creates a new property for each person that shows the bank account in his country's money.
Show less
No tags specified

Context

The NEW keyword constrcutor In the last example we saw that we had three objects that shared exactly the same keys, maybe not the same values, but they keys where the same! In such cases and instead of creating and initializing a new object by creating the same structure again and again, we can create an object constructor. An object constructor is a function that constructs objects given a designated schema. It's NOT an object, but a blueprint and every object that is created by this constructor will have this shape and these properties. Then the values can be parameterized exactly the same way we parameterize arguments in functions! Take a close look to the example above. We want to create many objects for people and we want to store the same piece of info there. Firstname, lastname and age. Then we can create a constructor that accepts three arguments. These arguments will be the values that will fill the properties for each object separately. On the left side we define the name of the properties. This can be anything but it's always good to be as descriptive as possible.  Then we create two objects from this constructor. In order to do this we use the NEW keyword which means that we create a new object from a specific constructor function. Thus we have created a re-usable way to instantiate objects! If a specific property has a fixed value, then instead of an argument we can put the fix value to this property. For example after line 23 we could add another property for every object that will be created from this constructor like: this.profession = 'student' Then both objects now have the profession property set as student. We don't need to put another argument because the value is fixed and not parameterized. It doesn't differ in other words from object  to object. O-3 Use a constructor for the previous exercise so you don't have to create an object literal from the beginning every time. Use arguments where you have to parameterize the values of the properties and fixed values where needed!
Show less
No tags specified

Context

Classes Another way to create a blueprint for object that will be born later is to define a class. This relatively new (ES2015 way) method requires the class keyword followed by the name of the class. Then we do exactly what we did before but this time inside a constructor function. This is exactly as before, and this is the function that will be executed any time an object uses this class alongside with the 'new' keyword in order to be created. Nothing changes (at least for now) and we can pass the arguments in order to populate our objects with different values inside the same properties. Take a loop at the previous example below, this has exactly the same result as before. Then why should someone bother with this syntax?
Show less
No tags specified

Context

Object inheritance Through the class syntax is very easy to create an hierarchy, a chain and create objects that don't hold necessarily their own properties and methods but they inherit from other classes. This is a core concept of object oriented programming and it's not specific to JS.  We can save a lot of typing by defining classes that hold properties and methods and then pass these methods (or bequeath if you like) to other classes or objects!.  In order for a class to inherit properties of another class we use the extends keyword on the child class. Then inside the child's class constructor function we use the super function, which is equivalent to the new keyword. Is a reference to the constructor function of the class we inherit from.   If you  at the example above, the jake object has all the properties of the Person constructor, those are it's OWN properties and a property 'nationality', which is bequeathed from the Greek class to the Person class through the super() function and the extends keyword that the Person class uses to reference any 'parent' classes and inherit from them. Already confused?let's make an exercise and see inheritance in full strength!
Show less
No tags specified

Mind Map

A mind map that describes how the class based inheritance works in ES6

Context

O-4 The tigers inheritance We will try to build our class inheritance in order to create instances of Tigers. As you may know there are two species of Tigers, the Siberian Tigers and the Bengal Tigers. That means every Tiger is unique, but also inherits characteristics from it's own species.  Let's see how we could build this structure step by step. At the beginning define a class named AllSpecies. This is the parent class and doesn't inherit from anyone. Define a constructor that is going to be used from all sub-classes that extend AllSpecies. In the AllSpecies constructor define 4 arguments. species, numOfEyes, numOfLegs, and hasTail. These indicate the species of the class that inherits from AllSpecies, how many eyes this species has, how many legs, and if this species has tail or not. Then it's time to create the Tiger class that extends from AllSpecies and uses inside it's constructor the super with these values. super('Tiger', 2, 4, true). The class Tiger inside it's own constructor also bequeaths some properties to all the sub-classes that will extend from Tiger class. These properties namely are: colorFur, eyeColor, region, eatMeet. The first three are going to be strings, the last is boolean as always. Once this is done create the BengalTiger class that extends Tiger class with the following values ('Orange-black', 'brown', 'India', true). That means that the colorFur is 'orange-black', the eye color is 'brown' etc. Create the SiberianTiger with the exact same way but use as values the following ('Black-white', 'blue', 'Siberia', false). Yes they are veggan! (at least for our example!).  Both Siberian and Bengal Tiger classes expose some properties to every unique tiger that will be created from them. These are the following: name, age, height, length and gender The last step is to instantiate two actual objects, one from each Tiger sub-class. For example: Create a unique bengal tiger with these properties ('Richard Parker', 15, 82, 226, 'male'); Create a siberian tiger with these properties ('The Nights King', 990, 88, 204, 'White Walker'); Console.log both tigers after you have stored them into their own variables and see if you can see all the properties they belong to them, plus the ones they inherited from the classes above! Extra Bonus: Create a function that prints the colorFur. This should be a method that every tiger should have regardless of type! You may want to take a look here first on how to do this. Anytime you want to visualize the task, take a look at the top of the screen.
Show less
No tags specified

Context

Object Iteration Objects are iterable data types. That means we can loop through each of an object's property and check it's value and many more.  This is done by using the for in loop. As shown above this strange for loop is comprised of 2 parts. In this case the 'prop' represents each of object's  keys and the 'jake' the object we iterate on.  We can choose then to print either the keys or the object. Prop is no specific keyword and it can be named as you like, it acts like a placeholder for every key.   Object iterations are very useful when used in combined with the hasOwnProperty native method to check for existing properties to nested objects. (Yep is possible!).
Show less
No tags specified

Context

O-5 Calculate average skills for every user Create 5 users that share the basic info like: firstname, lastname, htmlSkills, cssSkills, and jsSkills. So in total 5 arguments, inside the constructor use 3 properties.  this.firstName = firstName; this.lastName = lastName; this.skills = {html: htmlSkills, css: cssSkills, jsSkills}; Create a method that calculates the average of these 3 skills and returns the average. Find a way with what you have learned to loop through the skills property object and calculate average. Don't create a function for every object if it's possible. Use inheritance to do it in all in one fashion.
Show less
No tags specified

Context

O-6 Have i Seen this Movie? Create 5 objects that contain information about a specific movie each. Every object should contain the title of the movie as a property, the director's name, the year released, the starring actor, and if you have seen the movie or not. Put these objects into a bigger object and nest them inside it. Find a way by creating a function to print to the console only the names of the movies you have seen.
Show less
No tags specified

Context

O-7 Create a cashier balance Suppose you are a manager in a shop that sells clothes (like Karstadt or H&M etc).  The day begins, and the total balance is empty.  Your shop sells 3 kinds of goods.    t-shirts for 10$ each.    jeans for 30$ each.    jackets for 150$ each.   The shop has in stock 100 t-shirts, 100 jeans and 100 jackets. The total balance of the shop is 0. These are properties that belong to your shop object and are shared across all employees.   The shop has 3 different cashiers so we can serve 3 clients maximum at the same time. Create an object for every cashier and save inside:    the id of the cashier (from 1 to 3)    the fullname of the employee that works in the cashier now.    the number of customers this cashier has served. That is different for every cashier and begins with 0.    the balance of every cashier at any moment (begins empty). These properties belong to every employee (every cashier) separately.   Create a function that deals with any new buy from a customer the following way:    Accepts what the customer has bought and how much of it does he want.     If the quantity of the specified good the customer wants to buy is ok and does not surpass  the limit of our stock for this material, then we calculate the fee the customer needs to pay and we update first the cashier's balance and the total balance of the shop as well. In the end we increase the cashier's number of customers that have been served by 1.   Else if some material is not enough because we havn't so many pieces left, then cancel the order by consoling log a descriptive message to the console. In this case of course we don't update any other value. Ex.// cashier1.createSale(2, 2, 1) checks if the shop has 2 t-shirts left in stock, 2 jeans left and 1 jacket left. If some of these things is missing, we cancel the order. If not and all is fine, we update our stock (from 100 to 98 t-shirts etc), we add the cost of the order to cashier1 who made the sale, and of course we update the total balance of the shop with the cost of the order!   Additionally as bonus,  create another function that is for refunding in case the customer is not happy with the material he bought and he wants to give it back and take his money back. In such a case it should be clear what he returns back, so we can update the stock and how much of this material is left, and of course update the cashier's balance and the shop's balance in general (the whole calculation result should be deducted from both balances). Don't forget to decrease the number of customers that have been served from this cashier.   Be careful! Some of the properties that are getting changed are shared through all cashiers (like the total shop balance, or how much of a specific material is left) while others are different for every cashier separately (for every employee). You may want to think this first before you start implementing your architecture.
Show less
Show full summary Hide full summary