Submodule 12.2: JavaScript Objects

Site: ΕΛ/ΛΑΚ Moodle
Course: Study / Web Design and Web Development
Book: Submodule 12.2: JavaScript Objects
Printed by: Guest user
Date: Friday, 19 April 2024, 3:47 AM

Description

  • Objects Introduction
  • Access Object Properties
  • Changing, Adding and Deleting properties
  • Object Methods
  • The this keyword

Prerequisites for this submodule

You have to study the following educational material before starting this submodule:

Arrays

  • Definitions
  • Accessing an array
  • Array methods

Loops

  • for loop
  • while loop

Objects Introduction

Now you are ready to learn about JavaScript Objects.


What are objects?


As you may remember from the previous course, Variables are described as “containers” of a value ( string, number etc).

As you may remember Arrays are used to store multiple values in a single variable.

In the same way, Objects are variables themselves who act as containers for many variables.

The way objects are defined is:

var myObject = { 
name:"myName",
age:20,
job:"myJob"
};

The rules for the above syntax are:

  • The object is contained within curly braces.
  • The values are written as name : value pairs. In the above example, for the value age:”myAge”, the age is the name and the 20 is the value.
  • The name:value pairs are called properties
  • Names and values are separated by a colon
  • Each name:value pair, is separated from the others by commas

Access Object Properties

Let’s say that we have the object:

var darkChoco = {
cacao:"80%",
milk:"0%",
grams:100
};
var myChoco = "milk";

and we want to access its properties. The 3 different ways by which we can achieve this are:

        1. objectName.property

          Example: console.log(darkChoco.milk);

        2. objectName["property"]

          Example: console.log(darkChoco["milk"]);

        3. objectName[expression]

          Example: console.log(darkChoco[myChoco]);

Note that the 3rd way, it is only possible if the expression inside the [] is equivalent to a property name. In this case, the variable myChoco is equivalent with the property name milk.

Exercise

  1. Open your editor, create a new file and save it as exersice12.2.03.html in the folder "yourNameWEB2JS".
  2. Using the above code modify the file. The browser's output should be as shown in the following image:

Solution:

for/in Statement

In order to iterate over objects' properties we cannot use the classic for loops.

The syntax that allows as to iterate over all the properties of an object is:

for (var key in object)

var key can take any name. 

Example:

var darkChoco = {
cacao:"80%",
milk:"0%",
grams:100,

};

In order to iterate over this object we would write:

 for (var x in darkChoco) {
console.log ( x + ":" + darkChoco[x] );
} 

Exercise

Follow the next link. Right-click, select inspect and view the result in the Console tab. Next, click the "Sources" tab and click the HTML file to see the code:

 for/in Statement

Changing, Adding and Deleting properties

We can manipulate any property of a JavaScript object.

In order to change a property, we use the assignment operator.

For example for our object:

var darkChoco = { cacao:”80%”, milk:”0%”, grams:100 };

If we write

darkChoco. milk = “10%”;

we change the property from "0%" to "10%".

What do you think will happen if we write darkChoco["milk"]= "50%" ? Try it in the console.log();

Answer:

The new value of the milk will be “50”. When using the assignment operator in an object we can change any of its properties. So, in this case, we changed "0%" to "50%".

In order to add a property in an object we just write a new name:value pair. For example, if I wanted to add the property sugar:"10%" I would write:

darkChoco.sugar = "10%"

Moreover, we can remove object properties. This is done using the delete operator.

Example:

delete darkChoco.milk;

Exercise

  1. We have uploaded the 62.js file on our WEB server. The URL is https://cnc-wp1.ellak.gr/vasilisNameWEB2/JSvasilis/62.js. Copy this URL and paste it into your browser to see what this file includes.
  2. Open your editor, create a new file and save it as exersice12.2.04.html in the folder "yourNameWEB2JS".
  3. Add a link to the js file in your HTML code
  4. Using the theory discussed here, change, add and delete parts of the file. The browser's output should be as shown in the following image:

Solution:

 

Object Methods

Methods are the actions that can be applied to objects.

When a property of an object is a JavaScript function, we call it method.

Example:

var darkChoco = {
cacao:"80%",
milk:"0%",
grams:100,
getFullInfo : function () {
        return this.cacao + " " + this.milk + " " + this.grams;
    }
};

In the above example, if we are referring to getFullInfo, we are referring to the function as a value of that property. However, if we write getFullInfo followed by parenthesis, getFullInfo(), then we are refer to the method of that object.

To understand the difference between the two, go to your console and copy the code of the example. Next, do two tests. The first time type in the console darkChoco.getFullInfo; . The second time type darkChoco.getFullInfo(); What did you got each time?

Answer

Result for darkChoco.getFullInfo; : ƒ () { return this.cacao + " " + this.milk + " " + this.grams; }
Result for darkChoco.getFullInfo(); : "80% 0% 100"

In our example, you may have noticed the usage of a new expression, .this. The subject of our next chapter will be to explain this new keyword.

The this keyword

In the previous chapter, we saw the this keyword to be used inside an object. But what is this?

In general the keyword this refers to the context in which the function called is located. 

In our previous example:

var darkChoco = {
cacao:"80%",
milk:"0%",
grams:100,
getFullInfo : function () {
        return this.cacao + " " + this.milk + " " + this.grams;
    }
};

this refers to the values of cacao, milk and grams.

The meaning of this changes, depending on where we use it.

Now, open your console and type : this;

What do you see?

Answer

Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}

When there is no function related to this and we call it, the environment of this is the global context. In a web browser, any javaScript code not specified, has Window as its global object. Thus, in this case, this refers to the Window object.

Another very important usage of this is in the constructor functions. We will learn more about it in the next Sub-module.