JAVASCRIPT
Objects and Object Oriented Programming
Learn More -
Videos and source
code included
Get this Course
https://www.udemy.com/javascript-objects-
oop/?couponCode=SLIDESHARE
Course instructor : Laurence Svekis - providing online
training to over 500,000 students across hundreds of
courses and many platforms.
What are objects -
in JavaScript
When it comes to writing code there are mays ways to
create a solution.
object is a collection of properties, and a property is an
association between a name ( key) and a value. A property's
value can be a function, in which case the property is known
as a method.
Object Literal
notation
Objects contain data and can use that data to return
results.
// Literal notation
var myObj1 = {
stuff: "yes"
, greet: "hello"
};
const person = {
first: "Laurence"
, last: "Svekis"
, id: 100
, details: function () {
return `${this.last}, ${this.first} id#${this.id}`
}
}
TRY IT Create an object that reflects a car.
Add Color, make, model, price, year then for bonus
points add a few methods like drive and park. Output
to console.
const myCar = {};
myCar.color = "Black";
myCar.brand = "Ford";
myCar.make = "Mustang";
myCar.price = 50000;
myCar.year = 1965;
myCar.drive = function () {
console.log("I'm driving " + this.make + ", vrooom vrooom");
}
myCar.park = function () {
console.log("parking the car");
}
Solution Car object
const myCar1 = {
color: "red"
, model: "mustang"
, company: "ford"
, year: 2012
, price: 50000
};
console.log(myCar1.model);
console.log(myCar1['model']);
const temp = 'color';
console.log(myCar2[temp]);
Output Object Data Dot notation and Bracket notation
var myObj = {
"people": [ {
"firstName": "Mike"
, "lastName": "Smith"
, "age": 30
}, {
"firstName": "John"
, "lastName": "Jones"
, "age": 40
}]
};
for (let i = 0; i < myObj.people.length; i++) {
console.log(myObj.people[i].firstName + " " + myObj.people[i].lastName);
}
myObj.people.forEach(function (item) {
console.log(item.firstName + " " + item.lastName);
})
for (let prop in myObj.people) {
console.log(prop);
console.log(myObj.people[prop].firstName + " " + myObj.people[prop].lastName);
}
Object Data iterating contents
<body>
<script>
var myObj = {
"people": [ {
"firstName": "Mike"
, "lastName": "Smith"
, "age": 30
}, {
"firstName": "John"
, "lastName": "Jones"
, "age": 40
}]
};
myObj.people.forEach(function (item) {
console.log(item.firstName + " " + item.lastName);
let div = document.createElement('div');
div.innerHTML = `<h3>${item.firstName}</h3>${item.lastName}`;
div.style.border = "1px solid #ddd";
div.style.display = "inline-block";
div.style.width = "100px";
document.body.appendChild(div);
})
</script>
</body>
Creating Elements using Object Information to output content on web pages.
Challenge #1 Shopping CART
1. Create an array that contains a typical selection
of items you might find going shopping.
2. Create JavaScript code to output it on the page
as divs.
3. Add an event listener that when clicked adds
the selected item to a global object and
updating the quantity if the item is already
there.
4. Create a method within the new object that
calculates the subtotal
*You can add styling as needed to make it look nice :)
const items = [{
item: "Milk"
, id: 0
, cost: 5
}
, {
item: "Apple"
, id: 1
, cost: 1
}
, {
item: "Bread"
, id: 2
, cost: 2
}
, {
item: "Butter"
, id: 3
, cost: 3
}
]
Shopping Cart - #1
var cart = {};
items.forEach(function (ele) {
let div = document.createElement('div');
div.innerHTML = `<h3>${ele.item}</h3>$${ele.cost}`;
div.val = ele.id;
div.addEventListener('click', function () {
let namer = ele.item.toLowerCase();
if (!cart[namer]) {
cart[namer] = {
name: ele.item
, price: ele.cost
, qty: 1,
subtotal: function(){
return this.price * this.qty
}
}
}
else {
cart[namer].qty++;
}
})
div.style.border = "1px solid #ddd";
div.style.display = "inline-block";
document.body.appendChild(div);
})
Challenge #1 Shopping CART (part 2)
1. Add a cart on your page so that selected items
are visible.
2. Update it as new items are added
3. Add a total to the bottom
*Go shopping and enjoy.
const output = document.createElement('div');
document.body.appendChild(output);
items.forEach(function (ele) {
let div = document.createElement('div');
div.innerHTML = `<h3>${ele.item}</h3>$${ele.cost}`;
div.val = ele.id;
div.addEventListener('click', function () {
let namer = ele.item.toLowerCase();
if (!cart[namer]) {
cart[namer] = {
name: ele.item
, price: ele.cost
, qty: 1,
subtotal: function(){
return this.price * this.qty
}
}
}
else {
cart[namer].qty++;
}
relist();
})
})
Shopping Cart - #1
function relist() {
output.innerHTML = "";
console.log(cart);
let total = 0;
for (let pro in cart) {
let subTotal = cart[pro].subtotal();
total += subTotal;
output.innerHTML += `${cart[pro].name} $${cart[pro].price} x
${cart[pro].qty} = $${subTotal}<br>`
console.log(pro)
}
output.innerHTML += `$${total}`;
}
JavaScript Object
Oriented
Programming OOP
Objects are used to model and organize code. Grouping
similar items and tasks into what is known as a class.
It provide more flexibility and easier to extend on.
Class - it is the blueprint a template definition of an objects
properties and methods.
JavaScript Object
Constructor
notation
Uses class and new to construct the object. This makes it
easier to make many objects using the blueprint.
// Literal notation
var myObj1 = {
stuff: "yes"
, greet: "hello"
};
// Constructor notation
function Blueprint() {
this.stuff = "yes";
this.greet = "hello";
};
var myObj2 = new Blueprint();
var myObj3 = new Blueprint();
Constructor functions
Creating a new object using a function. The
constructor function is JavaScript's version of a
class.
Nothing is returned it defines properties and
methods
this keyword : name property will be equal to the
name value passed to the constructor call,
important tso they have their own values.
<script>
function Person(firstName, lastName) {
this.first = firstName;
this.last = lastName
this.greeting = function () {
console.log(`Hello ${this.first} ${this.last}`)
};
}
const tester = new Person('Laurence', 'Svekis');
console.log(tester.first);
tester.greeting();
</script>
TRY IT :
● Create several different objects using the constructor function.
● Invoke the greeting for each
TRY IT Its back.. But now use the function to construct the
object. Make a few cars…… Honda and Mustang and
more if you want. It’s easy :)
Also add a sell method that returns the minimum what
you want to sell it based on 90% of the price. Output
should match the sample.
const honda = new Car("Red", "Honda", "Accord", 45000, 2020);
const mustang = new Car("Black", "Ford", "Mustang", 50000, 1965);
function Car(color, brand, make, price, year) {
this.color = color;
this.brand = brand;
this.make = make;
this.price = price;
this.year = year;
this.tires = 4;
this.drive = function () {
console.log("I'm driving " + this.brand + " " + this.make + ", vrooom vrooom");
}
this.park = function () {
console.log("parking the " + this.brand);
}
this.sell = function () {
console.log("I want at least $" + this.price * .9 + " for the " + this.make + " I paid " + this.price);
}
}
Solution Car object
Challenge #2 Dice Game
1. Create an element on the page that can be
clicked
2. Create a constructor function to contain the
game functions calling it DiceGame
3. DiceGame Add option to roll the dice. Math
random 1-6
4. DiceGame Add option to check winner
5. In the click event add the roll for player and
computer using DiceGame
6. In the click event use DiceGame object to
determine winner and get result string.
7. Output the result to the clickable element
*You can add styling as needed to make it look nice :)
const game = new DiceGame();
const dice = document.createElement('div');
dice.textContent = "Roll Here";
document.body.appendChild(dice);
dice.addEventListener('click', function () {
let playerRoll = game.roll();
let compRoll = game.roll();
let winner = game.checker(playerRoll, compRoll);
console.log(winner);
dice.innerHTML = `Player ${playerRoll} vs Computer
${compRoll} <br> ${winner}`;
})
Dice Game - #2
function DiceGame() {
this.roll = function () {
this.result = Math.floor(Math.random() * 6) + 1;
return this.result;
}
this.checker = function (roll1, roll2) {
if (roll1 > roll2) {
return 'Player Wins';
}
else if (roll2 > roll1) {
return 'Computer Wins';
}
else {
return 'Tie';
}
}
}
Challenge #3 Shopping Cart
● Create DOM elements for input and adding
items to the store
● Add event listeners
● Create Objects for items
● Add shipping and tax to object
● Create Cart object
● Create adder method
● Create total cost method
● Create output of cart items
● Setup default item for testing
*Your application should be able to add items, click
new items and add them to a cart.
const output = document.createElement('div');
document.body.appendChild(output);
const output1 = document.createElement('div');
document.body.appendChild(output1);
const itemInput1 = document.createElement('input');
itemInput1.setAttribute('type', 'text');
itemInput1.setAttribute('placeholder', 'Item name');
output.appendChild(itemInput1);
const itemInput2 = document.createElement('input');
itemInput2.setAttribute('type', 'number');
itemInput2.setAttribute('placeholder', 'Cost');
output.appendChild(itemInput2);
const itemButton = document.createElement('button');
itemButton.textContent = "Add Item";
itemButton.addEventListener('click', addItem);
output.appendChild(itemButton);
const outputButton = document.createElement('button');
outputButton.textContent = "Output Cart";
outputButton.addEventListener('click', function () {
cart.output();
console.log(cart);
});
output.appendChild(outputButton);
const items = [];
const cart = new Cart();
Challenge #3 Shopping Cart
window.onload = function () {
itemInput1.value = "Milk";
itemInput2.value = 5;
addItem();
}
function addItem() {
let tempName = itemInput1.value || "Test";
let tempCost = itemInput2.value || 10;
let div = document.createElement('div');
div.innerHTML = `<h3>${tempName}</h3>$${tempCost}`;
div.style.border = "1px solid #ddd";
div.style.display = "inline-block";
div.style.width = "100px";
document.body.appendChild(div);
div.addEventListener('click', function () {
cart.adder(tempName, tempCost);
cart.output();
});
itemInput1.value = "";
itemInput2.value = "";
}
function Item(name, cost) {
this.name = name;
this.cost = cost;
this.withTax = function () {
return (this.cost * 1.15).toFixed(2);
}
this.shipping = function () {
return (this.cost * 1.05).toFixed(2);
}
}
function Cart() {
const myList = {};
this.totalCost = function () {
let total = 0;
for (let pro in myList) {
let subTotal = myList[pro].subtotal();
total += subTotal;
}
return total;
}
Challenge #3 Shopping Cart
this.output = function () {
let total = 0;
output1.innerHTML = "";
for (let pro in myList) {
let subTotal = myList[pro].subtotal();
total += subTotal;
output1.innerHTML += `${myList[pro].name}
$${myList[pro].price} x ${myList[pro].qty} = $${subTotal}<br>`
console.log(pro)
}
output1.innerHTML += `Final Total $${total}`;
}
this.adder = function (item, cost) {
let namer = item.toLowerCase();
if (!myList[namer]) {
myList[namer] = {
name: item
, price: cost
, qty: 1
, subtotal: function () {
return this.price * this.qty } } }
else {
myList[namer].qty++;
} } }
Congratulations on completing the section
This ebook uses https://developer.mozilla.org/en-US/docs/Web/JavaScript as a source for examples. Check out
more about JavaScript at MDN.
Find out more about my courses at http://www.discoveryvip.com/
Course instructor : Laurence Svekis -
providing online training to over
500,000 students across hundreds of
courses and many platforms.

More Related Content

PDF
Desarrollo de módulos en Drupal e integración con dispositivos móviles
PDF
Elm: give it a try
PDF
Cycle.js: Functional and Reactive
PDF
The jQuery Divide
PDF
Type safe embedded domain-specific languages
PDF
Modern Application Foundations: Underscore and Twitter Bootstrap
PDF
How else can you write the code in PHP?
PPTX
Jquery optimization-tips
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Elm: give it a try
Cycle.js: Functional and Reactive
The jQuery Divide
Type safe embedded domain-specific languages
Modern Application Foundations: Underscore and Twitter Bootstrap
How else can you write the code in PHP?
Jquery optimization-tips

What's hot (20)

PPTX
PPT
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
PDF
Chaining and function composition with lodash / underscore
PDF
Command-Oriented Architecture
PDF
MongoDB With Style
PDF
Writing Clean Code in Swift
KEY
Symfony2 Building on Alpha / Beta technology
PDF
Fabric.js @ Falsy Values
PDF
Learning jQuery in 30 minutes
PDF
"Coffee Script" in Brief
PDF
Swipe 2011 - iOS Gems
PDF
Prototype & jQuery
KEY
テストデータどうしてますか?
PDF
Cleaner, Leaner, Meaner: Refactoring your jQuery
PDF
JavaScript Fundamentals with Angular and Lodash
PDF
The Ring programming language version 1.7 book - Part 48 of 196
PDF
Functional JS for everyone - 4Developers
PDF
PhoneGap: Local Storage
PPTX
Academy PRO: ES2015
PDF
Automatically Spotting Cross-language Relations
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
Chaining and function composition with lodash / underscore
Command-Oriented Architecture
MongoDB With Style
Writing Clean Code in Swift
Symfony2 Building on Alpha / Beta technology
Fabric.js @ Falsy Values
Learning jQuery in 30 minutes
"Coffee Script" in Brief
Swipe 2011 - iOS Gems
Prototype & jQuery
テストデータどうしてますか?
Cleaner, Leaner, Meaner: Refactoring your jQuery
JavaScript Fundamentals with Angular and Lodash
The Ring programming language version 1.7 book - Part 48 of 196
Functional JS for everyone - 4Developers
PhoneGap: Local Storage
Academy PRO: ES2015
Automatically Spotting Cross-language Relations
Ad

Similar to JavaScript Objects and OOP Programming with JavaScript (20)

PDF
Javascript
PPTX
Object Oriented JavaScript
PDF
Introduction to ECMAScript 2015
PPTX
Java script
PDF
L7. Object in JS, CSE 202, BN11.pdf JavaScript
PPTX
Object oriented javascript
PPTX
Introduction to Advanced Javascript
PPTX
WEB222-lecture-4.pptx
PPTX
Javascript Objects and Functions
PPTX
8558537werr.pptx
PPTX
Javascript Objects and Functions
PPTX
PPTX
Cordova training : Day 4 - Advanced Javascript
PDF
Scalable JavaScript
PPTX
Prototype Framework
PPTX
What’s new in ECMAScript 6.0
PDF
Javascript
PDF
JavaScript Essentials
PPTX
Maintainable JavaScript 2012
PDF
GDI Seattle - Intro to JavaScript Class 2
Javascript
Object Oriented JavaScript
Introduction to ECMAScript 2015
Java script
L7. Object in JS, CSE 202, BN11.pdf JavaScript
Object oriented javascript
Introduction to Advanced Javascript
WEB222-lecture-4.pptx
Javascript Objects and Functions
8558537werr.pptx
Javascript Objects and Functions
Cordova training : Day 4 - Advanced Javascript
Scalable JavaScript
Prototype Framework
What’s new in ECMAScript 6.0
Javascript
JavaScript Essentials
Maintainable JavaScript 2012
GDI Seattle - Intro to JavaScript Class 2
Ad

More from Laurence Svekis ✔ (20)

PDF
Quiz JavaScript Objects Learn more about JavaScript
PDF
JavaScript Lessons 2023 V2
PDF
JavaScript Lessons 2023
PDF
Top 10 Linkedin Tips Guide 2023
PDF
JavaScript Interview Questions 2023
PDF
Code examples javascript ebook
PDF
Javascript projects Course
PDF
10 java script projects full source code
PDF
Chrome DevTools Introduction 2020 Web Developers Guide
PDF
Brackets code editor guide
PDF
Web hosting get start online
PDF
JavaScript guide 2020 Learn JavaScript
PDF
Web hosting Free Hosting
PDF
Web development resources brackets
PPTX
Google Apps Script for Beginners- Amazing Things with Code
PPTX
Local SQLite Database with Node for beginners
PDF
Introduction to Node js for beginners + game project
PPTX
JavaScript DOM - Dynamic interactive Code
PPTX
JavaScript Advanced - Useful methods to power up your code
PPTX
Monster JavaScript Course - 50+ projects and applications
Quiz JavaScript Objects Learn more about JavaScript
JavaScript Lessons 2023 V2
JavaScript Lessons 2023
Top 10 Linkedin Tips Guide 2023
JavaScript Interview Questions 2023
Code examples javascript ebook
Javascript projects Course
10 java script projects full source code
Chrome DevTools Introduction 2020 Web Developers Guide
Brackets code editor guide
Web hosting get start online
JavaScript guide 2020 Learn JavaScript
Web hosting Free Hosting
Web development resources brackets
Google Apps Script for Beginners- Amazing Things with Code
Local SQLite Database with Node for beginners
Introduction to Node js for beginners + game project
JavaScript DOM - Dynamic interactive Code
JavaScript Advanced - Useful methods to power up your code
Monster JavaScript Course - 50+ projects and applications

Recently uploaded (20)

PDF
semiconductor packaging in vlsi design fab
PPTX
Core Concepts of Personalized Learning and Virtual Learning Environments
PPTX
Module on health assessment of CHN. pptx
PDF
M.Tech in Aerospace Engineering | BIT Mesra
PDF
Skin Care and Cosmetic Ingredients Dictionary ( PDFDrive ).pdf
PPTX
What’s under the hood: Parsing standardized learning content for AI
PDF
plant tissues class 6-7 mcqs chatgpt.pdf
PPTX
Climate Change and Its Global Impact.pptx
PDF
fundamentals-of-heat-and-mass-transfer-6th-edition_incropera.pdf
PDF
Race Reva University – Shaping Future Leaders in Artificial Intelligence
PDF
Laparoscopic Colorectal Surgery at WLH Hospital
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PDF
LEARNERS WITH ADDITIONAL NEEDS ProfEd Topic
PDF
Climate and Adaptation MCQs class 7 from chatgpt
PDF
LIFE & LIVING TRILOGY- PART (1) WHO ARE WE.pdf
PDF
Journal of Dental Science - UDMY (2020).pdf
PPT
REGULATION OF RESPIRATION lecture note 200L [Autosaved]-1-1.ppt
PPTX
UNIT_2-__LIPIDS[1].pptx.................
PDF
Fun with Grammar (Communicative Activities for the Azar Grammar Series)
PDF
Compact First Student's Book Cambridge Official
semiconductor packaging in vlsi design fab
Core Concepts of Personalized Learning and Virtual Learning Environments
Module on health assessment of CHN. pptx
M.Tech in Aerospace Engineering | BIT Mesra
Skin Care and Cosmetic Ingredients Dictionary ( PDFDrive ).pdf
What’s under the hood: Parsing standardized learning content for AI
plant tissues class 6-7 mcqs chatgpt.pdf
Climate Change and Its Global Impact.pptx
fundamentals-of-heat-and-mass-transfer-6th-edition_incropera.pdf
Race Reva University – Shaping Future Leaders in Artificial Intelligence
Laparoscopic Colorectal Surgery at WLH Hospital
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
LEARNERS WITH ADDITIONAL NEEDS ProfEd Topic
Climate and Adaptation MCQs class 7 from chatgpt
LIFE & LIVING TRILOGY- PART (1) WHO ARE WE.pdf
Journal of Dental Science - UDMY (2020).pdf
REGULATION OF RESPIRATION lecture note 200L [Autosaved]-1-1.ppt
UNIT_2-__LIPIDS[1].pptx.................
Fun with Grammar (Communicative Activities for the Azar Grammar Series)
Compact First Student's Book Cambridge Official

JavaScript Objects and OOP Programming with JavaScript

  • 1. JAVASCRIPT Objects and Object Oriented Programming
  • 2. Learn More - Videos and source code included Get this Course https://www.udemy.com/javascript-objects- oop/?couponCode=SLIDESHARE Course instructor : Laurence Svekis - providing online training to over 500,000 students across hundreds of courses and many platforms.
  • 3. What are objects - in JavaScript When it comes to writing code there are mays ways to create a solution. object is a collection of properties, and a property is an association between a name ( key) and a value. A property's value can be a function, in which case the property is known as a method.
  • 4. Object Literal notation Objects contain data and can use that data to return results. // Literal notation var myObj1 = { stuff: "yes" , greet: "hello" }; const person = { first: "Laurence" , last: "Svekis" , id: 100 , details: function () { return `${this.last}, ${this.first} id#${this.id}` } }
  • 5. TRY IT Create an object that reflects a car. Add Color, make, model, price, year then for bonus points add a few methods like drive and park. Output to console.
  • 6. const myCar = {}; myCar.color = "Black"; myCar.brand = "Ford"; myCar.make = "Mustang"; myCar.price = 50000; myCar.year = 1965; myCar.drive = function () { console.log("I'm driving " + this.make + ", vrooom vrooom"); } myCar.park = function () { console.log("parking the car"); } Solution Car object
  • 7. const myCar1 = { color: "red" , model: "mustang" , company: "ford" , year: 2012 , price: 50000 }; console.log(myCar1.model); console.log(myCar1['model']); const temp = 'color'; console.log(myCar2[temp]); Output Object Data Dot notation and Bracket notation
  • 8. var myObj = { "people": [ { "firstName": "Mike" , "lastName": "Smith" , "age": 30 }, { "firstName": "John" , "lastName": "Jones" , "age": 40 }] }; for (let i = 0; i < myObj.people.length; i++) { console.log(myObj.people[i].firstName + " " + myObj.people[i].lastName); } myObj.people.forEach(function (item) { console.log(item.firstName + " " + item.lastName); }) for (let prop in myObj.people) { console.log(prop); console.log(myObj.people[prop].firstName + " " + myObj.people[prop].lastName); } Object Data iterating contents
  • 9. <body> <script> var myObj = { "people": [ { "firstName": "Mike" , "lastName": "Smith" , "age": 30 }, { "firstName": "John" , "lastName": "Jones" , "age": 40 }] }; myObj.people.forEach(function (item) { console.log(item.firstName + " " + item.lastName); let div = document.createElement('div'); div.innerHTML = `<h3>${item.firstName}</h3>${item.lastName}`; div.style.border = "1px solid #ddd"; div.style.display = "inline-block"; div.style.width = "100px"; document.body.appendChild(div); }) </script> </body> Creating Elements using Object Information to output content on web pages.
  • 10. Challenge #1 Shopping CART 1. Create an array that contains a typical selection of items you might find going shopping. 2. Create JavaScript code to output it on the page as divs. 3. Add an event listener that when clicked adds the selected item to a global object and updating the quantity if the item is already there. 4. Create a method within the new object that calculates the subtotal *You can add styling as needed to make it look nice :)
  • 11. const items = [{ item: "Milk" , id: 0 , cost: 5 } , { item: "Apple" , id: 1 , cost: 1 } , { item: "Bread" , id: 2 , cost: 2 } , { item: "Butter" , id: 3 , cost: 3 } ] Shopping Cart - #1 var cart = {}; items.forEach(function (ele) { let div = document.createElement('div'); div.innerHTML = `<h3>${ele.item}</h3>$${ele.cost}`; div.val = ele.id; div.addEventListener('click', function () { let namer = ele.item.toLowerCase(); if (!cart[namer]) { cart[namer] = { name: ele.item , price: ele.cost , qty: 1, subtotal: function(){ return this.price * this.qty } } } else { cart[namer].qty++; } }) div.style.border = "1px solid #ddd"; div.style.display = "inline-block"; document.body.appendChild(div); })
  • 12. Challenge #1 Shopping CART (part 2) 1. Add a cart on your page so that selected items are visible. 2. Update it as new items are added 3. Add a total to the bottom *Go shopping and enjoy.
  • 13. const output = document.createElement('div'); document.body.appendChild(output); items.forEach(function (ele) { let div = document.createElement('div'); div.innerHTML = `<h3>${ele.item}</h3>$${ele.cost}`; div.val = ele.id; div.addEventListener('click', function () { let namer = ele.item.toLowerCase(); if (!cart[namer]) { cart[namer] = { name: ele.item , price: ele.cost , qty: 1, subtotal: function(){ return this.price * this.qty } } } else { cart[namer].qty++; } relist(); }) }) Shopping Cart - #1 function relist() { output.innerHTML = ""; console.log(cart); let total = 0; for (let pro in cart) { let subTotal = cart[pro].subtotal(); total += subTotal; output.innerHTML += `${cart[pro].name} $${cart[pro].price} x ${cart[pro].qty} = $${subTotal}<br>` console.log(pro) } output.innerHTML += `$${total}`; }
  • 14. JavaScript Object Oriented Programming OOP Objects are used to model and organize code. Grouping similar items and tasks into what is known as a class. It provide more flexibility and easier to extend on. Class - it is the blueprint a template definition of an objects properties and methods.
  • 15. JavaScript Object Constructor notation Uses class and new to construct the object. This makes it easier to make many objects using the blueprint. // Literal notation var myObj1 = { stuff: "yes" , greet: "hello" }; // Constructor notation function Blueprint() { this.stuff = "yes"; this.greet = "hello"; }; var myObj2 = new Blueprint(); var myObj3 = new Blueprint();
  • 16. Constructor functions Creating a new object using a function. The constructor function is JavaScript's version of a class. Nothing is returned it defines properties and methods this keyword : name property will be equal to the name value passed to the constructor call, important tso they have their own values. <script> function Person(firstName, lastName) { this.first = firstName; this.last = lastName this.greeting = function () { console.log(`Hello ${this.first} ${this.last}`) }; } const tester = new Person('Laurence', 'Svekis'); console.log(tester.first); tester.greeting(); </script> TRY IT : ● Create several different objects using the constructor function. ● Invoke the greeting for each
  • 17. TRY IT Its back.. But now use the function to construct the object. Make a few cars…… Honda and Mustang and more if you want. It’s easy :) Also add a sell method that returns the minimum what you want to sell it based on 90% of the price. Output should match the sample.
  • 18. const honda = new Car("Red", "Honda", "Accord", 45000, 2020); const mustang = new Car("Black", "Ford", "Mustang", 50000, 1965); function Car(color, brand, make, price, year) { this.color = color; this.brand = brand; this.make = make; this.price = price; this.year = year; this.tires = 4; this.drive = function () { console.log("I'm driving " + this.brand + " " + this.make + ", vrooom vrooom"); } this.park = function () { console.log("parking the " + this.brand); } this.sell = function () { console.log("I want at least $" + this.price * .9 + " for the " + this.make + " I paid " + this.price); } } Solution Car object
  • 19. Challenge #2 Dice Game 1. Create an element on the page that can be clicked 2. Create a constructor function to contain the game functions calling it DiceGame 3. DiceGame Add option to roll the dice. Math random 1-6 4. DiceGame Add option to check winner 5. In the click event add the roll for player and computer using DiceGame 6. In the click event use DiceGame object to determine winner and get result string. 7. Output the result to the clickable element *You can add styling as needed to make it look nice :)
  • 20. const game = new DiceGame(); const dice = document.createElement('div'); dice.textContent = "Roll Here"; document.body.appendChild(dice); dice.addEventListener('click', function () { let playerRoll = game.roll(); let compRoll = game.roll(); let winner = game.checker(playerRoll, compRoll); console.log(winner); dice.innerHTML = `Player ${playerRoll} vs Computer ${compRoll} <br> ${winner}`; }) Dice Game - #2 function DiceGame() { this.roll = function () { this.result = Math.floor(Math.random() * 6) + 1; return this.result; } this.checker = function (roll1, roll2) { if (roll1 > roll2) { return 'Player Wins'; } else if (roll2 > roll1) { return 'Computer Wins'; } else { return 'Tie'; } } }
  • 21. Challenge #3 Shopping Cart ● Create DOM elements for input and adding items to the store ● Add event listeners ● Create Objects for items ● Add shipping and tax to object ● Create Cart object ● Create adder method ● Create total cost method ● Create output of cart items ● Setup default item for testing *Your application should be able to add items, click new items and add them to a cart.
  • 22. const output = document.createElement('div'); document.body.appendChild(output); const output1 = document.createElement('div'); document.body.appendChild(output1); const itemInput1 = document.createElement('input'); itemInput1.setAttribute('type', 'text'); itemInput1.setAttribute('placeholder', 'Item name'); output.appendChild(itemInput1); const itemInput2 = document.createElement('input'); itemInput2.setAttribute('type', 'number'); itemInput2.setAttribute('placeholder', 'Cost'); output.appendChild(itemInput2); const itemButton = document.createElement('button'); itemButton.textContent = "Add Item"; itemButton.addEventListener('click', addItem); output.appendChild(itemButton); const outputButton = document.createElement('button'); outputButton.textContent = "Output Cart"; outputButton.addEventListener('click', function () { cart.output(); console.log(cart); }); output.appendChild(outputButton); const items = []; const cart = new Cart(); Challenge #3 Shopping Cart window.onload = function () { itemInput1.value = "Milk"; itemInput2.value = 5; addItem(); } function addItem() { let tempName = itemInput1.value || "Test"; let tempCost = itemInput2.value || 10; let div = document.createElement('div'); div.innerHTML = `<h3>${tempName}</h3>$${tempCost}`; div.style.border = "1px solid #ddd"; div.style.display = "inline-block"; div.style.width = "100px"; document.body.appendChild(div); div.addEventListener('click', function () { cart.adder(tempName, tempCost); cart.output(); }); itemInput1.value = ""; itemInput2.value = ""; }
  • 23. function Item(name, cost) { this.name = name; this.cost = cost; this.withTax = function () { return (this.cost * 1.15).toFixed(2); } this.shipping = function () { return (this.cost * 1.05).toFixed(2); } } function Cart() { const myList = {}; this.totalCost = function () { let total = 0; for (let pro in myList) { let subTotal = myList[pro].subtotal(); total += subTotal; } return total; } Challenge #3 Shopping Cart this.output = function () { let total = 0; output1.innerHTML = ""; for (let pro in myList) { let subTotal = myList[pro].subtotal(); total += subTotal; output1.innerHTML += `${myList[pro].name} $${myList[pro].price} x ${myList[pro].qty} = $${subTotal}<br>` console.log(pro) } output1.innerHTML += `Final Total $${total}`; } this.adder = function (item, cost) { let namer = item.toLowerCase(); if (!myList[namer]) { myList[namer] = { name: item , price: cost , qty: 1 , subtotal: function () { return this.price * this.qty } } } else { myList[namer].qty++; } } }
  • 24. Congratulations on completing the section This ebook uses https://developer.mozilla.org/en-US/docs/Web/JavaScript as a source for examples. Check out more about JavaScript at MDN. Find out more about my courses at http://www.discoveryvip.com/ Course instructor : Laurence Svekis - providing online training to over 500,000 students across hundreds of courses and many platforms.