SlideShare una empresa de Scribd logo
1 de 24
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.

Más contenido relacionado

La actualidad más candente

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 / underscoreNicolas Carlo
 
Command-Oriented Architecture
Command-Oriented ArchitectureCommand-Oriented Architecture
Command-Oriented ArchitectureLuiz Messias
 
Writing Clean Code in Swift
Writing Clean Code in SwiftWriting Clean Code in Swift
Writing Clean Code in SwiftDerek Lee Boire
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Fabric.js @ Falsy Values
Fabric.js @ Falsy ValuesFabric.js @ Falsy Values
Fabric.js @ Falsy ValuesJuriy Zaytsev
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutesSimon Willison
 
"Coffee Script" in Brief
"Coffee Script" in Brief"Coffee Script" in Brief
"Coffee Script" in BriefNat Weerawan
 
Swipe 2011 - iOS Gems
Swipe 2011 - iOS GemsSwipe 2011 - iOS Gems
Swipe 2011 - iOS GemsKevin O'Neill
 
Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQueryRemy 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 LodashBret 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 196Mahmoud Samir Fayed
 
Functional JS for everyone - 4Developers
Functional JS for everyone - 4DevelopersFunctional JS for everyone - 4Developers
Functional JS for everyone - 4DevelopersBartek Witczak
 
Automatically Spotting Cross-language Relations
Automatically Spotting Cross-language RelationsAutomatically Spotting Cross-language Relations
Automatically Spotting Cross-language RelationsFederico Tomassetti
 

La actualidad más candente (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 a 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 codeLaurence Svekis ✔
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScriptAndrew Dupont
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
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 181Mahmoud 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 212Mahmoud Samir Fayed
 
Paris js extensions
Paris js extensionsParis js extensions
Paris js extensionserwanl
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1saydin_soft
 
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 31Mahmoud Samir Fayed
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
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 a 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
 

Más de 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 JavaScriptLaurence Svekis ✔
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023Laurence 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 codeLaurence 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 GuideLaurence Svekis ✔
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptLaurence Svekis ✔
 
Web development resources brackets
Web development resources bracketsWeb development resources brackets
Web development resources bracketsLaurence 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 CodeLaurence 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 beginnersLaurence 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 projectLaurence Svekis ✔
 
JavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive CodeJavaScript DOM - Dynamic interactive Code
JavaScript DOM - Dynamic interactive CodeLaurence 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 applicationsLaurence Svekis ✔
 
JavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereJavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereLaurence Svekis ✔
 

Más de 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
 

Último

Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 

Último (20)

Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 

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.