SlideShare a Scribd company logo
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

What's hot

Lenses
LensesLenses
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
Sencha
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
Nicolas Carlo
 
Command-Oriented Architecture
Command-Oriented ArchitectureCommand-Oriented Architecture
Command-Oriented Architecture
Luiz Messias
 
MongoDB With Style
MongoDB With StyleMongoDB With Style
MongoDB With Style
Gabriele Lana
 
Writing Clean Code in Swift
Writing Clean Code in SwiftWriting Clean Code in Swift
Writing Clean Code in Swift
Derek Lee Boire
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
Daniel Knell
 
Fabric.js @ Falsy Values
Fabric.js @ Falsy ValuesFabric.js @ Falsy Values
Fabric.js @ Falsy Values
Juriy Zaytsev
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
Simon Willison
 
"Coffee Script" in Brief
"Coffee Script" in Brief"Coffee Script" in Brief
"Coffee Script" in Brief
Nat Weerawan
 
Swipe 2011 - iOS Gems
Swipe 2011 - iOS GemsSwipe 2011 - iOS Gems
Swipe 2011 - iOS Gems
Kevin O'Neill
 
Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQuery
Remy Sharp
 
テストデータどうしてますか?
テストデータどうしてますか?テストデータどうしてますか?
テストデータどうしてますか?
Yuki Shibazaki
 
Cleaner, Leaner, Meaner: Refactoring your jQuery
Cleaner, Leaner, Meaner: Refactoring your jQueryCleaner, Leaner, Meaner: Refactoring your jQuery
Cleaner, Leaner, Meaner: Refactoring your jQueryRebecca Murphey
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
Bret Little
 
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.7 book - Part 48 of 196
Mahmoud Samir Fayed
 
Functional JS for everyone - 4Developers
Functional JS for everyone - 4DevelopersFunctional JS for everyone - 4Developers
Functional JS for everyone - 4Developers
Bartek Witczak
 
PhoneGap: Local Storage
PhoneGap: Local StoragePhoneGap: Local Storage
PhoneGap: Local Storage
Ivano Malavolta
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
Binary Studio
 
Automatically Spotting Cross-language Relations
Automatically Spotting Cross-language RelationsAutomatically Spotting Cross-language Relations
Automatically Spotting Cross-language Relations
Federico Tomassetti
 

What's hot (20)

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

Similar to JavaScript Objects and OOP Programming with JavaScript

JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
Laurence Svekis ✔
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
Andrew Dupont
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
Scala on Your Phone
Scala on Your PhoneScala on Your Phone
Scala on Your Phone
Michael Galpin
 
The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181
Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212
Mahmoud Samir Fayed
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensions
erwanl
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
jeresig
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1saydin_soft
 
Build your own entity with Drupal
Build your own entity with DrupalBuild your own entity with Drupal
Build your own entity with Drupal
Marco Vito Moscaritolo
 
The Ring programming language version 1.5 book - Part 3 of 31
The Ring programming language version 1.5 book - Part 3 of 31The Ring programming language version 1.5 book - Part 3 of 31
The Ring programming language version 1.5 book - Part 3 of 31
Mahmoud Samir Fayed
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Tsuyoshi Yamamoto
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
André Faria Gomes
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
Rodica Dada
 
mobl
moblmobl
mobl
zefhemel
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j queryMd. Ziaul Haq
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KThomas Fuchs
 

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

JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Scala on Your Phone
Scala on Your PhoneScala on Your Phone
Scala on Your Phone
 
The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181
 
The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensions
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
 
Build your own entity with Drupal
Build your own entity with DrupalBuild your own entity with Drupal
Build your own entity with Drupal
 
The Ring programming language version 1.5 book - Part 3 of 31
The Ring programming language version 1.5 book - Part 3 of 31The Ring programming language version 1.5 book - Part 3 of 31
The Ring programming language version 1.5 book - Part 3 of 31
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Java Script
Java ScriptJava Script
Java Script
 
mobl
moblmobl
mobl
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j query
 
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KZepto.js, a jQuery-compatible mobile JavaScript framework in 2K
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2K
 

More from Laurence Svekis ✔

Quiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScriptQuiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScript
Laurence Svekis ✔
 
JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
Laurence Svekis ✔
 
JavaScript Lessons 2023
JavaScript Lessons 2023JavaScript Lessons 2023
JavaScript Lessons 2023
Laurence Svekis ✔
 
Top 10 Linkedin Tips Guide 2023
Top 10 Linkedin Tips Guide 2023Top 10 Linkedin Tips Guide 2023
Top 10 Linkedin Tips Guide 2023
Laurence Svekis ✔
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
Laurence Svekis ✔
 
Code examples javascript ebook
Code examples javascript ebookCode examples javascript ebook
Code examples javascript ebook
Laurence Svekis ✔
 
Javascript projects Course
Javascript projects CourseJavascript projects Course
Javascript projects Course
Laurence Svekis ✔
 
10 java script projects full source code
10 java script projects full source code10 java script projects full source code
10 java script projects full source code
Laurence Svekis ✔
 
Chrome DevTools Introduction 2020 Web Developers Guide
Chrome DevTools Introduction 2020 Web Developers GuideChrome DevTools Introduction 2020 Web Developers Guide
Chrome DevTools Introduction 2020 Web Developers Guide
Laurence Svekis ✔
 
Brackets code editor guide
Brackets code editor guideBrackets code editor guide
Brackets code editor guide
Laurence Svekis ✔
 
Web hosting get start online
Web hosting get start onlineWeb hosting get start online
Web hosting get start online
Laurence Svekis ✔
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
Web hosting Free Hosting
Web hosting Free HostingWeb hosting Free Hosting
Web hosting Free Hosting
Laurence Svekis ✔
 
Web development resources brackets
Web development resources bracketsWeb development resources brackets
Web development resources brackets
Laurence Svekis ✔
 
Google Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with CodeGoogle Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with Code
Laurence Svekis ✔
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
Laurence Svekis ✔
 
Introduction to Node js for beginners + game project
Introduction to Node js for beginners + game projectIntroduction to Node js for beginners + game project
Introduction to Node js for beginners + game project
Laurence Svekis ✔
 
JavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive CodeJavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive Code
Laurence Svekis ✔
 
Monster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applicationsMonster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applications
Laurence Svekis ✔
 
JavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereJavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript Here
Laurence Svekis ✔
 

More from Laurence Svekis ✔ (20)

Quiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScriptQuiz JavaScript Objects Learn more about JavaScript
Quiz JavaScript Objects Learn more about JavaScript
 
JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
 
JavaScript Lessons 2023
JavaScript Lessons 2023JavaScript Lessons 2023
JavaScript Lessons 2023
 
Top 10 Linkedin Tips Guide 2023
Top 10 Linkedin Tips Guide 2023Top 10 Linkedin Tips Guide 2023
Top 10 Linkedin Tips Guide 2023
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
Code examples javascript ebook
Code examples javascript ebookCode examples javascript ebook
Code examples javascript ebook
 
Javascript projects Course
Javascript projects CourseJavascript projects Course
Javascript projects Course
 
10 java script projects full source code
10 java script projects full source code10 java script projects full source code
10 java script projects full source code
 
Chrome DevTools Introduction 2020 Web Developers Guide
Chrome DevTools Introduction 2020 Web Developers GuideChrome DevTools Introduction 2020 Web Developers Guide
Chrome DevTools Introduction 2020 Web Developers Guide
 
Brackets code editor guide
Brackets code editor guideBrackets code editor guide
Brackets code editor guide
 
Web hosting get start online
Web hosting get start onlineWeb hosting get start online
Web hosting get start online
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
 
Web hosting Free Hosting
Web hosting Free HostingWeb hosting Free Hosting
Web hosting Free Hosting
 
Web development resources brackets
Web development resources bracketsWeb development resources brackets
Web development resources brackets
 
Google Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with CodeGoogle Apps Script for Beginners- Amazing Things with Code
Google Apps Script for Beginners- Amazing Things with Code
 
Local SQLite Database with Node for beginners
Local SQLite Database with Node for beginnersLocal SQLite Database with Node for beginners
Local SQLite Database with Node for beginners
 
Introduction to Node js for beginners + game project
Introduction to Node js for beginners + game projectIntroduction to Node js for beginners + game project
Introduction to Node js for beginners + game project
 
JavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive CodeJavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive Code
 
Monster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applicationsMonster JavaScript Course - 50+ projects and applications
Monster JavaScript Course - 50+ projects and applications
 
JavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereJavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript Here
 

Recently uploaded

How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 

Recently uploaded (20)

How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 

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.