Objects & Classes: Softuni Team
Objects & Classes: Softuni Team
Objects & Classes: Softuni Team
SoftUni Team
Technical Trainers
Software University
https://softuni.bg
Table of Contents
1. Objects
Object and Properties
Looping Through Objects
2. JSON
3. Classes
Definition
Constructor
Fields
2
Have a Question?
sli.do
#js-advanced
3
Objects
Objects and Properties
What is an Object?
An object is a collection of fields, and a field is an
association between a name (or key) and a value
Objects are a reference data type
You define (and create) a JavaScript object with an
object literal: let person = {
firstName: "John",
lastName: "Doe",
age: 50
};
5
Variables Holding References
The in-memory value of a reference type is the
reference itself (a memory address)
let x = {name: 'John'}; x
name John
let y = x; y
y.name = "John";
console.log(x.name); // John
6
Object Properties
A property of an object can be explained as a
variable that is attached to the object
Object properties are basically the same as ordinary
JavaScript variables, except for the attachment to
objects
Property Name Property Value
firstName John
lastName Doe
age 50
7
Assigning and Accessing Properties
Simple dot-notation
let person = { name: 'Peter' };
person.age = 21; // { name: 'Peter', age: 21 }
console.log(person.name); // Peter
Bracket-notation
person['job-title'] = 'Trainer';
console.log(person['job-title']) // Trainer
console.log(person.job-title) // ReferenceError
8
Assigning and Accessing Properties
Unassigned properties of an object are undefined
let person = { name: 'Peter' };
console.log(person.lastName); // undefined
9
Object Methods
Objects can also have methods
Methods are actions that can be performed on objects
Methods are stored in properties as function definitions
let person = {
firstName: "John",
lastName: "Doe",
age: function (myAge) {
return `My age is ${myAge}!` }
};
console.log(person.age(21)); // My age is 21!
10
Deleting Properties
person.age = 21;
/*Object {name: {first: 'John', last: 'Doe'},
age: 21}*/
person['gender'] = 'male';
/*Object {name: {first: 'John', last: 'Doe'},
age: 21,
gender: 'male'}*/
delete person.gender;
/*Object {name: {first: 'John', last: 'Doe'},
age: 21}*/
11
Comparing Objects
Two variables, two distinct objects with the same properties
let fruit = {name: 'apple'};
let fruitbear = {name: 'apple'};
fruit == fruitbear; // return false
fruit === fruitbear; // return false
Two variables, a single object
let fruit = { name: 'apple' };
let fruitbear = fruit;
// Assign fruit object reference to fruitbear
// Here fruit and fruitbear are pointing to same object
fruit == fruitbear; // return true
fruit === fruitbear; // return true
12
Looping Through Objects
Object Keys and Values
let course = { name: 'JS Core', hall: 'Open Source' };
let keys = Object.keys(course);
console.log(keys); // [ 'name', 'hall' ]
if (course.hasOwnProperty('name')) {
console.log(course.name); // JS Core
}
let values = Object.values(course);
console.log(values); // [ 'JS Core', 'Open Source' ]
if (values.includes('JS Core')) {
console.log("Found 'JS Core' value");
}
14
For… in Loop
for … in - iterates a specified variable over all the
enumerable properties of an object
let obj = {a: 1, b: 2, c: 3};
for (const key in obj) {
console.log(`obj.${key} = ${obj[key]}`);
}
// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"
15
For…of Loop
The for...of statement creates a loop iterating over iterable
objects
let obj = {a: 1, b: 2, c: 3};
for (const key of Object.keys(obj)) {
console.log(`obj.${key} = ${obj[key]}`);
}
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"
for (const val of Object.values(obj)) {console.log(val);}
// 1
// 2
// 3
16
{}
JSON
JavaScript Object Notation
JavaScript Object Notation
It's a data interchange format
It's language independent - syntax is like JavaScript
object syntax, but the JSON format is text only
Is "self-describing" and easy to understand:
{
"employees": [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
]
}
18
Syntax Rules
In JSON:
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
JSON only takes double quotes ""
{
"employees": [{ "firstName": "John", "lastName": "Doe" }]
}
19
Parsing from Strings
A common use of JSON is to read data from a web server, and
display the data in a web page
Use the JavaScript built-in function JSON.parse() to convert the
JSON format into a JavaScript object:
20
Converting to String
Use JSON.stringify() to convert objects into a string:
let obj = { name: "John", age: 30, city: "New York" };
let myJSON = JSON.stringify(obj);
console.log(myJSON);// {"name":"John","age":30,"city":"New York"}
<table>
<tr><th>Name</th><th>Price</th></tr>
<tr><td>Tomatoes & Chips</td><td>2.35</td></tr>
<tr><td>J&B Chocolate</td><td>0.96</td></tr>
</table>
22
Solution: 3. From JSON to HTML Table
function JsonToHtmlTable(json) {
let arr = JSON.parse(json);
let outputArr = ["<table>"];
outputArr.push(makeKeyRow(arr));
arr.forEach((obj) => outputArr.push(makeValueRow(obj)));
outputArr.push("</table>");
function makeKeyRow(arr) { // ToDo }
function makeValueRow(obj) { // ToDo };
function escapeHtml(value) { // ToDo };
console.log(outputArr.join('\n'));
}
23
Classes
Definition, Constructor, Prototype, Fields
Class Definition
Structure for objects
Classes define:
Data (properties, attributes)
Actions (behavior)
One class may have many instances (objects)
The class syntax has two components:
Class Expressions and Class Declarations
25
Defining Class
Class declaration: Class expression:
class Rectangle { let Rectangle = class Rectangle2 {
constructor(height, width) { constructor(height, width) {
this.height = height; this.height = height;
this.width = width; this.width = width;
} }
}; };
28
Prototype Methods
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Method
calcArea() { return this.height * this.width; }
}
const square = new Rectangle(10, 10);
console.log(square.calcArea()); // 100
29
Accessor Properties
class Circle {
constructor(radius) { this.radius = radius; }
Property getter
get diameter() { return 2 * this.radius; }
let c = new Circle(2);
console.log(`Radius: ${c.radius}`); // 2
console.log(`Diameter: ${c.diameter}`); // 4
console.log(`Area: ${c.area}`); // 12.566370614359172
c.diameter = 1.6;
console.log(`Radius: ${c.radius}`); // 0.8
console.log(`Diameter: ${c.diameter}`); // 1.6
console.log(`Area: ${c.area}`); // 2.0106192982974678
31
Static Methods
The static keyword defines a static method for a class
static staticMethod() { return 'Static method has been called'}
class Example {
#privateField;
constructor() {
this.#privateField = 42
this.#randomField = 666 // Syntax error
}
}
const instance = new Example ()
instance.#privateField === 42 // Syntax error
33
Accessing Private Properties
Only the class which defines the private static field can access
the field.
To make a private property readable/writable from any function,
it's common to define getters/setters
class Example {
#privateField;
constructor() { this.#privateField = 42 }
get privateField() { return this.#privateField }
}
35
Solution: 7. Person
class Person {
constructor(fName, lName, age, email) {
this.firstName = fName;
this.lastName = lName;
this.age = age;
this.email = email;
}
toString() {
return `${this.firstName} ${this.lastName}
(age: ${this.age}, email: ${this.email})`
}
}
36
Problem: 8. Get People
Write a function that returns an array of Person objects
Use the class from the previous task
There will be no input, the data is static and matches on this data
37
Solution: 8. Get People
class Person {
constructor(firstName, lastName, age, email) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.email = email;
}
toString() {
return `${this.firstName} ${this.lastName}
(age: ${this.age}, email: ${this.email})`
}
}
return [new Person('Anna', 'Simpson', 22, '[email protected]'),
... //TODO for the rest of the people
38
Summary
Objects
…
Hold key-value pairs called properties
…
Methods are actions that can be
…performed on objects
JSON - data interchange format
Classes - structure for objects, that may define:
Methods
Accessor properties
39
Questions?
© SoftUni – https://softuni.bg Copyrighted document. Unauthorized copy, reproduction or use is not permitted.
Trainings @ Software University (SoftUni)
Software University – High-Quality Education,
Profession and Job for Software Developers
softuni.bg, softuni.org
Software University Foundation
softuni.foundation
Software University @ Facebook
facebook.com/SoftwareUniversity
Software University Forums
forum.softuni.bg
4
License
42