Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
76 views

Objects & Classes: Softuni Team

Uploaded by

Mariyan Tsvetkov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views

Objects & Classes: Softuni Team

Uploaded by

Mariyan Tsvetkov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Objects & Classes

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:

let data = '{ "manager":{"firstName":"John","lastName":"Doe"} }';


let obj = JSON.parse(data);
console.log(obj.manager.lastName) // Doe

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"}

 You can do the same for arrays


let arr = [ "John", "Peter", "Sally", "Jane" ];
let myJSON = JSON.stringify(arr);
console.log(myJSON); // ["John","Peter","Sally","Jane"]

 JSON.stringify() format the string for presentation


21
Problem: 3. From JSON to HTML Table
 Read a JSON string, holding array of JS objects (key / value pairs)
 Print the objects as HTML table like shown below
[{"Name":"Tomatoes & Chips","Price":2.35},
{"Name":"J&B Chocolate","Price":0.96}]

<table>
    <tr><th>Name</th><th>Price</th></tr>
    <tr><td>Tomatoes &amp; Chips</td><td>2.35</td></tr>
    <tr><td>J&amp;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;
    }     }
}; };

 uses class keyword  uses class keyword


 constructor defines class data  constructor defines class data
 can be named or unnamed
26
Hoisting
 Function declarations are hoisted and class declarations
are not
 You first need to declare your class and then access it,
otherwise a ReferenceError will be thrown
const p = new Rectangle(); // ReferenceError
class Rectangle {}

 Class expressions are subject to the same hoisting


restrictions
27
Class Body
 The part of class that is in curly brackets {}
 Here you define class members, such as methods
class Circle {
    constructor(r) {
        this.r = r;
    }
};

 The constructor is a special method for creating and initializing


an object created with a class

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; }

Property setter     set diameter(diameter) {


        this.radius = diameter / 2;
    }
Read-only     get area() {
property "area"
        return Math.PI * this.radius * this.radius;
    }
}
30
Accessor Properties in Action

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'}

 Called without instantiating their class and cannot be called


through a class instance
 To call a static method of the same class, you can use the this
keyword
static anotherStaticMethod() {
    return this.staticMethod() + ' from another method';
}
32
Private Properties
 Private instance fields are declared with #names
 It is a syntax error to refer to #names from out of scope

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 }
}

const instance = new Example()


console.log(instance.private); //42
34
Problem: 7. Person
 Write a class that represent a personal record
 It needs to have the following properties:
 firstName, lastName, age and email
 And a toString() method
let person = new Person('Anna', 'Simpson', 22, 'anna@yahoo.com');
console.log(person.toString());
// Anna Simpson (age: 22, email: anna@yahoo.com)

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

First Name Last Name Age Email


Anna Simpson 22 anna@yahoo.com
SoftUni
Stephan Johnson 25
Gabriel Peterson 24 g.p@gmail.com

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, 'anna@yahoo.com'),
... //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

 This course (slides, examples, demos, exercises, homework,


documents, videos and other assets) is copyrighted content
 Unauthorized copy, reproduction or use is illegal
 © SoftUni – https://about.softuni.bg/
 © Software University – https://softuni.bg

42

You might also like