SlideShare ist ein Scribd-Unternehmen logo
1 von 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.

Weitere ähnliche Inhalte

Was ist angesagt?

Cleaner, Leaner, Meaner: Refactoring your jQuery
Cleaner, Leaner, Meaner: Refactoring your jQueryCleaner, Leaner, Meaner: Refactoring your jQuery
Cleaner, Leaner, Meaner: Refactoring your jQuery
Rebecca Murphey
 

Was ist angesagt? (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
 

Ähnlich wie 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 ✔
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
偉格 高
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
saydin_soft
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j query
Md. 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 2K
Thomas Fuchs
 

Ähnlich wie 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
 

Mehr von Laurence Svekis ✔

JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
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 projects Course
Javascript projects CourseJavascript projects Course
Javascript projects Course
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 ✔
 

Mehr von 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
 

Kürzlich hochgeladen

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
heathfieldcps1
 

Kürzlich hochgeladen (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
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
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
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
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
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
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
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
 

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.