SlideShare a Scribd company logo
1 of 56
JavaScript, Sixth Edition
Chapter 7
Using Object-Oriented JavaScript
JavaScript, Sixth Edition 2
Objectives
When you complete this chapter, you will be able to:
• Explain basic concepts related to object-oriented
programming
• Use the Date, Number, and Math objects
• Define your own custom JavaScript objects
JavaScript, Sixth Edition 3
Introduction to Object-Oriented
Programming
• Object-oriented programming
– Allows reuse of code without having to copy or
recreate it
JavaScript, Sixth Edition 4
Reusing Software Objects
• Object-oriented programming (OOP)
– Creating reusable software objects
• Easily incorporated into multiple programs
• Object
– Programming code and data treated as an individual
unit or component
– Also called a component
• Data
– Information contained within variables or other types
of storage structures
JavaScript, Sixth Edition 5
Reusing Software Objects (cont’d.)
• Objects range from simple controls to entire
programs
• Popular object-oriented programming languages
– C++, Java, Visual Basic
JavaScript, Sixth Edition 6
Figure 7-1 Programming with objects
Reusing Software Objects (cont’d.)
JavaScript, Sixth Edition 7
What Is Encapsulation?
• Encapsulated objects
– Code and data contained within the object itself
• Encapsulation places code inside a “black box”
• Interface
– Elements required for program to communicate with
an object
• Principle of information hiding
– Any methods and properties other programmers do
not need to access should be hidden
JavaScript, Sixth Edition 8
What Is Encapsulation? (cont’d.)
• Advantages of encapsulation
– Reduces code complexity
– Prevents accidental bugs and stealing of code
• Programming object and its interface
– Compare to a handheld calculator
Figure 7-2 Calculator interface
JavaScript, Sixth Edition 9
What Is Encapsulation? (cont’d.)
• Document object is encapsulated (black box)
– getElementById() method
• Part of the interface JavaScript uses to communicate
with the Document object
• Microsoft Word: example of an object and its
interface
Figure 7-3 Using the interface for the Document object
Understanding Classes
• Classes
– Grouping of code, methods, attributes, etc., making
up an object
• Instance
– Object created from an existing class
• Instantiate: create an object from an existing class
• Instance of an object inherits its methods and
properties from a class
• Objects in the browser object model
– Part of the web browser
– No need to instantiate them to use them
JavaScript, Sixth Edition 10
JavaScript, Sixth Edition 11
Using Built-In JavaScript Classes
Table 7-1 Built-in JavaScript classes
JavaScript, Sixth Edition 12
Using Built-In JavaScript Classes
(cont’d.)
• Instantiating an object
– Some of the built-in JavaScript objects used
directly in code
– Some objects require programmer to instantiate a
new object
– Example: Math object’s PI(π) property in a script
// calculate the area of a circle based on its radius
function calcCircleArea() {
var r = document.getElementById("radius").value;
var area = Math.PI * Math.pow(r, 2); // area is pi times ↵
radius squared
return area;
}
JavaScript, Sixth Edition 13
Using Built-In JavaScript Classes
(cont’d.)
• Instantiating an object (cont’d.)
– Can instantiate Array object using array literal
• Example: var deptHeads = [];
– Can instantiate empty generic object using object
literal
• Example: var accountsPayable = {};
• Generic object literal uses curly braces around value
– Can't use object literal for Date object
• Must use constructor
• Example: var today = new Date();
JavaScript, Sixth Edition 14
Using Built-In JavaScript Classes
(cont’d.)
• Performing garbage collection
– Garbage collection
• Cleaning up, or reclaiming, memory reserved by a
program
– Declaring a variable or instantiating a new object
• Reserves memory for the variable or object
– JavaScript knows when a program no longer needs a
variable or object
• Automatically cleans up the memory
JavaScript, Sixth Edition 15
Using the Date, Number, and Math
Classes
• Three of most commonly used JavaScript classes:
– Date, Number, and Math
JavaScript, Sixth Edition 16
Manipulating the Date and Time with
the Date Class
• Date class
– Methods and properties for manipulating the date and
time
– Allows use of a specific date or time element in
JavaScript programs
Table 7-2 Date class constructors
JavaScript, Sixth Edition 17
Manipulating the Date and Time with
the Date Class (cont’d.)
• Example:
– var today = new Date();
– Month and year date representation in a Date object
– Stored using numbers matching actual date and year
• Days of the week and months of the year
– Stored using numeric representations
• Starting with zero: similar to an array
• Example:
– var independenceDay = new Date(1776, 6, 4);
JavaScript, Sixth Edition 18
Manipulating the Date and Time with
the Date Class (cont’d.)
• After creating a new Date object
– Manipulate date and time in the variable using the
Date class methods
• Date and time in a Date object
– Not updated over time like a clock
– Date object contains the static (unchanging) date and
time
• Set at the moment the JavaScript code instantiates the
object
JavaScript, Sixth Edition 19
Table 7-3 Commonly used methods of the Date class (continues)
Manipulating the Date and Time with
the Date Class (cont’d.)
JavaScript, Sixth Edition 20
Table 7-3 Commonly used methods of the Date class
Manipulating the Date and Time with
the Date Class (cont’d.)
JavaScript, Sixth Edition 21
Manipulating the Date and Time with
the Date Class (cont’d.)
• Each portion of a Date object can be retrieved and
modified using the Date object methods
– Examples:
var curDate = new Date();
curDate.getDate();
• Displaying the full text for days and months
– Use a conditional statement to check the value
returned by the getDay() or getMonth() method
– Example:
• if/else construct to print the full text for the day of
the week returned by the getDay() method
JavaScript, Sixth Edition 22
var today = new Date();
var curDay = today.getDay();
var weekday;
if (curDay === 0) {
weekday = "Sunday";
} else if (curDay === 1) {
weekday = "Monday";
} else if (curDay === 2) {
weekday = "Tuesday";
} else if (curDay === 3) {
weekday = "Wednesday";
} else if (curDay === 4) {
weekday = "Thursday";
Manipulating the Date and Time with
the Date Class (cont’d.)
JavaScript, Sixth Edition 23
var today = new Date();
var months = ["January","February","March",↵
"April","May","June",↵
"July","August","September",↵
"October","November","December"];
var curMonth = months[today.getMonth()];
Manipulating the Date and Time with
the Date Class (cont’d.)
• Example: include an array named months
– 12 elements assigned full text names of the months
JavaScript, Sixth Edition 24
Manipulating Numbers with the
Number Class
• Number class
– Methods for manipulating numbers and properties
containing static values
• Representing some numeric limitations in the
JavaScript language
– Can append the name of any Number class method
or property
• To the name of an existing variable containing a
numeric value
JavaScript, Sixth Edition 25
Manipulating Numbers with the
Number Class (cont’d.)
• Using Number class methods
Table 7-4 Number class methods
JavaScript, Sixth Edition 26
Manipulating Numbers with the
Number Class (cont’d.)
• Using Number class methods (cont’d.)
– Primary reason for using any of the “to” methods
• To convert a number to a string value with a specific
number of decimal places
– toFixed() method
• Most useful Number class method
– toLocaleString() method
• Converts a number to a string formatted with local
numeric formatting conventions
JavaScript, Sixth Edition 27
Manipulating Numbers with the
Number Class (cont’d.)
• Accessing Number class properties
Table 7-5 Number class properties
JavaScript, Sixth Edition 28
Performing Math Functions with the
Math Class
• Math class
– Methods and properties for mathematical calculations
• Cannot instantiate a Math object using a statement
such as: var mathCalc = new Math();
– Use the Math object and one of its methods or
properties directly in the code
• Example:
var curNumber = 144;
var squareRoot = Math.sqrt(curNumber); // returns 12
JavaScript, Sixth Edition 29
Table 7-6 Math class methods
Performing Math Functions with the
Math Class (cont’d.)
JavaScript, Sixth Edition 30
Table 7-7 Math class properties
Performing Math Functions with the
Math Class (cont’d.)
JavaScript, Sixth Edition 31
Performing Math Functions with the
Math Class (cont’d.)
• Example:
– Use the PI property to calculate the area of a circle
based on its radius
• Code uses the pow() method to raise the radius value
to second power, and the round() method to round
the value returned to the nearest whole number
var radius = 25;
var area = Math.PI * Math.pow(radius, 2);
var roundedArea = Math.round(area); // returns 1963
JavaScript, Sixth Edition 32
Defining Custom JavaScript Objects
• JavaScript: not a true object-oriented programming
language
– Cannot create classes in JavaScript
– Instead, called an object-based language
• Can define custom objects
– Not encapsulated
– Useful to replicate the same functionality an unknown
number of times in a script
JavaScript, Sixth Edition 33
Declaring Basic Custom Objects
• Use the Object object
– var objectName = new Object();
– var objectName = {};
• Can assign properties to the object
– Append property name to the object name with a
period
JavaScript, Sixth Edition 34
Declaring Basic Custom Objects
(cont'd.)
• Add properties using dot syntax
– Object name followed by dot followed by property
name
– Example:
InventoryList.inventoryDate = new Date(2017, 11, 31);
JavaScript, Sixth Edition 35
Declaring Basic Custom Objects
(cont'd.)
• Can assign values to the properties of an object
when object first instantiated
• Example:
var PerformanceTickets = {
customerName: "Claudia Salomon",
performanceName: "Swan Lake",
ticketQuantity: 2,
performanceDate: new Date(2017, 6, 18, 20)
};
JavaScript, Sixth Edition 36
Declaring Sub-Objects
• Value of a property can be another object
– called a sub-object
– Example–order object with address sub-object:
var order = {
orderNumber: "F5987",
address: {
street: "1 Main St",
city: "Farmington",
state: "NY",
zip: "14425"
Referring to Object Properties as
Associative Arrays
• Associative array
– An array whose elements are referred to with an
alphanumeric key instead of an index number
• Can also use associative array syntax to refer to the
properties of an object
• With associative arrays
– Can dynamically build property names at runtime
JavaScript, Sixth Edition 37
JavaScript, Sixth Edition 38
Referring to Object Properties as
Associative Arrays (cont'd.)
• Can use associative array syntax to refer to the
properties of an object
• Example:
var stopLightColors = {
stop: "red",
caution: "yellow",
go: "green"
};
stopLightColors["caution"];
JavaScript, Sixth Edition 39
Referring to Object Properties as
Associative Arrays (cont'd.)
• Can easily reference property names that contain
numbers
– Example:
var order = {
item1: "KJ2435J",
price1: 23.95,
item2: "AW23454",
price2: 44.99,
item3: "2346J3B",
price3: 9.95
};
JavaScript, Sixth Edition 40
Referring to Object Properties as
Associative Arrays (cont'd.)
• Can easily reference property names that contain
numbers (cont'd.)
– To create order summary:
for (var i = 1; i < 4; i++) {
document.getElementById("itemList").innerHTML +=↵
"<p class='item'>" + order["item" + i] + "</p>";
document.getElementById("itemList").innerHTML +=↵
"<p class='price'>" + order["price" + i] + "</p>";
};
JavaScript, Sixth Edition 41
Referring to Object Properties as
Associative Arrays (cont'd.)
• Can also write generic code to add new object
properties that incorporate numbers
– Example—adding items to shopping cart:
totalItems += 1; // increment counter of items in order
currentItem = document.getElementById("itemName").innerHTML;
currentPrice = document.getElementById("itemPrice").innerHTML;
newItemPropertyName = "item" + totalItems; // "item4"
newPricePropertyName = "price" + totalItems; // "price4"
order.newItemPropertyName = currentItem; // order.item4 = (name)
order.newPricePropertyName = currentPrice;
// order.price4 = (price);
JavaScript, Sixth Edition 42
Creating Methods
• Object method simply a function with a name within
the object
• Two ways to add method to object
– Provide code for method in object
– Reference external function
JavaScript, Sixth Edition 43
Creating Methods (cont'd.)
• Specify method name with anonymous function as
value
– Example:
var order = {
items: {},
generateInvoice: function() {
// function statements
}
};
JavaScript, Sixth Edition 44
Creating Methods (cont'd.)
• Specify method name with existing function as value
– Example:
– Reference to existing function cannot have
parentheses
function processOrder() {
// function statements
}
var order = {
items: {},
generateInvoice: processOrder
};
JavaScript, Sixth Edition 45
Enumerating custom object properties
• Custom objects can contain dozens of properties
• To execute the same statement or command block
for all the properties within a custom object
– Use the for/in statement
– Looping statement similar to the for statement
• Syntax
for (variable in object) {
statement(s);
}
JavaScript, Sixth Edition 46
Enumerating custom object properties
(cont'd.)
• for/in statement enumerates, or assigns an index
to, each property in an object
• Typical use:
– validate properties within an object
JavaScript, Sixth Edition 47
var item={
itemNumber: "KJ2435J",
itemPrice: 23.95,
itemInstock: true,
itemShipDate: new Date(2017, 6, 18),
};
for (prop in order) {
if (order[prop] === "") {
order.generateErrorMessage();
Enumerating custom object properties
(cont’d.)
• Example—checking for empty values:
JavaScript, Sixth Edition 48
Deleting Properties
• Use the delete operator
• Syntax
delete object.property
• Example:
delete order.itemInStock;
JavaScript, Sixth Edition 49
Defining Constructor Functions
• Constructor function
– Used as the basis for a custom object
– Also known as object definition
• JavaScript objects
– Inherit all the variables and statements of the
constructor function on which they are based
• All JavaScript functions
– Can serve as a constructor
JavaScript, Sixth Edition 50
Defining Constructor Functions
(cont’d.)
• Example:
– Define a function that can serve as a constructor
function
function Order(number, order, payment, ship) {
this.customerNumber = number;
this.orderDate = order;
this.paymentMethod = payment;
this.shippingDate = ship;
}
JavaScript, Sixth Edition 51
Adding Methods to a Constructor
Function
• Can create a function to use as an object method
– Refer to object properties with this reference
– Example:
function displayOrderInfo() {
var summaryDiv = document.getElementById("summarySection");
summaryDiv.innerHTML += ("<p>Customer: " +↵
this.customerNumber + "</p>");
summaryDiv.innerHTML += ("<p>Order Date: " +↵
this.orderDate.toLocaleString()+ "</p>");
summaryDiv.innerHTML += ("<p>Payment: " +↵
this.paymentMethod + "</p>");
summaryDiv.innerHTML += ("<p>Ship Date: " +↵
JavaScript, Sixth Edition 52
Using the prototype Property
• After instantiating a new object
– Can assign additional object properties
• Use a period
• New property only available to that specific object
• prototype property
– Built-in property that specifies the constructor from
which an object was instantiated
– When used with the name of the constructor function
• Any new properties you create will also be available to
the constructor function
Using the prototype Property
(cont’d.)
• Object definitions can use the prototype property
to extend other object definitions
– Can create a new object based on an existing object
JavaScript, Sixth Edition 53
Summary
• Object-oriented programming (or OOP)
– The creation of reusable software objects
• Reusable software objects
– Called components
• Object
– Programming code and data treated as an individual
unit or component
• Objects are encapsulated
• Interface represents elements required for a source
program to communicate with an object
JavaScript, Sixth Edition 54
Summary (cont’d.)
• Principle of information hiding
• Code, methods, attributes, and other information
that make up an object
– Organized using classes
• Instance
– Object created from an existing class
• An object inherits the characteristics of the class on
which it is based
• Date class contains methods and properties for
manipulating the date and time
JavaScript, Sixth Edition 55
Summary (cont’d.)
• Number class contains methods for manipulating
numbers and properties
• Math class contains methods and properties for
performing mathematical calculations
• Can define custom object
– object literal
• Can create template for custom objects
– constructor function
• this keyword refers to object that called function
• prototype property specifies object's constructor
JavaScript, Sixth Edition 56

More Related Content

What's hot

3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOMJalpesh Vasa
 
javascript objects
javascript objectsjavascript objects
javascript objectsVijay Kalyan
 
Java Collection
Java CollectionJava Collection
Java CollectionDeeptiJava
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic FunctionsWebStackAcademy
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions WebStackAcademy
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced FunctionsWebStackAcademy
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals WebStackAcademy
 
#pugMi - DDD - Value objects
#pugMi - DDD - Value objects#pugMi - DDD - Value objects
#pugMi - DDD - Value objectsSimone Gentili
 
JavaScript objects and functions
JavaScript objects and functionsJavaScript objects and functions
JavaScript objects and functionsVictor Verhaagen
 
Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"Fwdays
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript ObjectsReem Alattas
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scriptingmichid
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - OperatorsWebStackAcademy
 
12. session 12 java script objects
12. session 12   java script objects12. session 12   java script objects
12. session 12 java script objectsPhúc Đỗ
 

What's hot (19)

3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
javaScript and jQuery
javaScript and jQueryjavaScript and jQuery
javaScript and jQuery
 
Java Collection
Java CollectionJava Collection
Java Collection
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
Core Java Programming Language (JSE) : Chapter X - I/O Fundamentals
 
#pugMi - DDD - Value objects
#pugMi - DDD - Value objects#pugMi - DDD - Value objects
#pugMi - DDD - Value objects
 
JavaScript objects and functions
JavaScript objects and functionsJavaScript objects and functions
JavaScript objects and functions
 
Calypso browser
Calypso browserCalypso browser
Calypso browser
 
cb streams - gavin pickin
cb streams - gavin pickincb streams - gavin pickin
cb streams - gavin pickin
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
 
Linq
LinqLinq
Linq
 
Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"Nikita Galkin "Looking for the right tech stack for GraphQL application"
Nikita Galkin "Looking for the right tech stack for GraphQL application"
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
 
12. session 12 java script objects
12. session 12   java script objects12. session 12   java script objects
12. session 12 java script objects
 

Similar to 9781305078444 ppt ch07

Ch 7: Object-Oriented JavaScript
Ch 7: Object-Oriented JavaScriptCh 7: Object-Oriented JavaScript
Ch 7: Object-Oriented JavaScriptdcomfort6819
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan collegeahmed hmed
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and ClassesIntro C# Book
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03Terry Yoast
 
Chapter 14 Exploring Object-based Programming
Chapter 14 Exploring Object-based ProgrammingChapter 14 Exploring Object-based Programming
Chapter 14 Exploring Object-based ProgrammingDr. Ahmed Al Zaidy
 
tutorial 10 Exploring Arrays, Loops, and conditional statements.ppt
tutorial 10 Exploring Arrays, Loops, and conditional statements.ppttutorial 10 Exploring Arrays, Loops, and conditional statements.ppt
tutorial 10 Exploring Arrays, Loops, and conditional statements.pptAbdisamedAdam
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in javaagorolabs
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and ClassesSvetlin Nakov
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
Chapter 10 Exploring arrays, loops, and conditional statements
Chapter 10 Exploring arrays, loops, and conditional statementsChapter 10 Exploring arrays, loops, and conditional statements
Chapter 10 Exploring arrays, loops, and conditional statementsDr. Ahmed Al Zaidy
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 
Adding To the Leaf Pile
Adding To the Leaf PileAdding To the Leaf Pile
Adding To the Leaf Pilestuporglue
 

Similar to 9781305078444 ppt ch07 (20)

Ch 7: Object-Oriented JavaScript
Ch 7: Object-Oriented JavaScriptCh 7: Object-Oriented JavaScript
Ch 7: Object-Oriented JavaScript
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan college
 
Java chapter 4
Java chapter 4Java chapter 4
Java chapter 4
 
Step By Step Guide to Learn R
Step By Step Guide to Learn RStep By Step Guide to Learn R
Step By Step Guide to Learn R
 
Extending Node.js using C++
Extending Node.js using C++Extending Node.js using C++
Extending Node.js using C++
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and Classes
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03
 
Chapter 14 Exploring Object-based Programming
Chapter 14 Exploring Object-based ProgrammingChapter 14 Exploring Object-based Programming
Chapter 14 Exploring Object-based Programming
 
2java Oop
2java Oop2java Oop
2java Oop
 
tutorial 10 Exploring Arrays, Loops, and conditional statements.ppt
tutorial 10 Exploring Arrays, Loops, and conditional statements.ppttutorial 10 Exploring Arrays, Loops, and conditional statements.ppt
tutorial 10 Exploring Arrays, Loops, and conditional statements.ppt
 
Classes1
Classes1Classes1
Classes1
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
Chapter 10 Exploring arrays, loops, and conditional statements
Chapter 10 Exploring arrays, loops, and conditional statementsChapter 10 Exploring arrays, loops, and conditional statements
Chapter 10 Exploring arrays, loops, and conditional statements
 
GraphQL-ify your APIs
GraphQL-ify your APIsGraphQL-ify your APIs
GraphQL-ify your APIs
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Adding To the Leaf Pile
Adding To the Leaf PileAdding To the Leaf Pile
Adding To the Leaf Pile
 
Lecture3.pdf
Lecture3.pdfLecture3.pdf
Lecture3.pdf
 

More from Terry Yoast

9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10Terry Yoast
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01Terry Yoast
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13Terry Yoast
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18Terry Yoast
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17Terry Yoast
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16Terry Yoast
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15Terry Yoast
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14Terry Yoast
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12Terry Yoast
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11Terry Yoast
 
9781337102087 ppt ch10
9781337102087 ppt ch109781337102087 ppt ch10
9781337102087 ppt ch10Terry Yoast
 
9781337102087 ppt ch09
9781337102087 ppt ch099781337102087 ppt ch09
9781337102087 ppt ch09Terry Yoast
 
9781337102087 ppt ch08
9781337102087 ppt ch089781337102087 ppt ch08
9781337102087 ppt ch08Terry Yoast
 
9781337102087 ppt ch06
9781337102087 ppt ch069781337102087 ppt ch06
9781337102087 ppt ch06Terry Yoast
 
9781337102087 ppt ch05
9781337102087 ppt ch059781337102087 ppt ch05
9781337102087 ppt ch05Terry Yoast
 
9781337102087 ppt ch04
9781337102087 ppt ch049781337102087 ppt ch04
9781337102087 ppt ch04Terry Yoast
 
9780538745840 ppt ch10
9780538745840 ppt ch109780538745840 ppt ch10
9780538745840 ppt ch10Terry Yoast
 
9780538745840 ppt ch09
9780538745840 ppt ch099780538745840 ppt ch09
9780538745840 ppt ch09Terry Yoast
 
9780538745840 ppt ch08
9780538745840 ppt ch089780538745840 ppt ch08
9780538745840 ppt ch08Terry Yoast
 
9780538745840 ppt ch07
9780538745840 ppt ch079780538745840 ppt ch07
9780538745840 ppt ch07Terry Yoast
 

More from Terry Yoast (20)

9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11
 
9781337102087 ppt ch10
9781337102087 ppt ch109781337102087 ppt ch10
9781337102087 ppt ch10
 
9781337102087 ppt ch09
9781337102087 ppt ch099781337102087 ppt ch09
9781337102087 ppt ch09
 
9781337102087 ppt ch08
9781337102087 ppt ch089781337102087 ppt ch08
9781337102087 ppt ch08
 
9781337102087 ppt ch06
9781337102087 ppt ch069781337102087 ppt ch06
9781337102087 ppt ch06
 
9781337102087 ppt ch05
9781337102087 ppt ch059781337102087 ppt ch05
9781337102087 ppt ch05
 
9781337102087 ppt ch04
9781337102087 ppt ch049781337102087 ppt ch04
9781337102087 ppt ch04
 
9780538745840 ppt ch10
9780538745840 ppt ch109780538745840 ppt ch10
9780538745840 ppt ch10
 
9780538745840 ppt ch09
9780538745840 ppt ch099780538745840 ppt ch09
9780538745840 ppt ch09
 
9780538745840 ppt ch08
9780538745840 ppt ch089780538745840 ppt ch08
9780538745840 ppt ch08
 
9780538745840 ppt ch07
9780538745840 ppt ch079780538745840 ppt ch07
9780538745840 ppt ch07
 

Recently uploaded

GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxnelietumpap1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 

Recently uploaded (20)

YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Q4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptxQ4 English4 Week3 PPT Melcnmg-based.pptx
Q4 English4 Week3 PPT Melcnmg-based.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 

9781305078444 ppt ch07

  • 1. JavaScript, Sixth Edition Chapter 7 Using Object-Oriented JavaScript
  • 2. JavaScript, Sixth Edition 2 Objectives When you complete this chapter, you will be able to: • Explain basic concepts related to object-oriented programming • Use the Date, Number, and Math objects • Define your own custom JavaScript objects
  • 3. JavaScript, Sixth Edition 3 Introduction to Object-Oriented Programming • Object-oriented programming – Allows reuse of code without having to copy or recreate it
  • 4. JavaScript, Sixth Edition 4 Reusing Software Objects • Object-oriented programming (OOP) – Creating reusable software objects • Easily incorporated into multiple programs • Object – Programming code and data treated as an individual unit or component – Also called a component • Data – Information contained within variables or other types of storage structures
  • 5. JavaScript, Sixth Edition 5 Reusing Software Objects (cont’d.) • Objects range from simple controls to entire programs • Popular object-oriented programming languages – C++, Java, Visual Basic
  • 6. JavaScript, Sixth Edition 6 Figure 7-1 Programming with objects Reusing Software Objects (cont’d.)
  • 7. JavaScript, Sixth Edition 7 What Is Encapsulation? • Encapsulated objects – Code and data contained within the object itself • Encapsulation places code inside a “black box” • Interface – Elements required for program to communicate with an object • Principle of information hiding – Any methods and properties other programmers do not need to access should be hidden
  • 8. JavaScript, Sixth Edition 8 What Is Encapsulation? (cont’d.) • Advantages of encapsulation – Reduces code complexity – Prevents accidental bugs and stealing of code • Programming object and its interface – Compare to a handheld calculator Figure 7-2 Calculator interface
  • 9. JavaScript, Sixth Edition 9 What Is Encapsulation? (cont’d.) • Document object is encapsulated (black box) – getElementById() method • Part of the interface JavaScript uses to communicate with the Document object • Microsoft Word: example of an object and its interface Figure 7-3 Using the interface for the Document object
  • 10. Understanding Classes • Classes – Grouping of code, methods, attributes, etc., making up an object • Instance – Object created from an existing class • Instantiate: create an object from an existing class • Instance of an object inherits its methods and properties from a class • Objects in the browser object model – Part of the web browser – No need to instantiate them to use them JavaScript, Sixth Edition 10
  • 11. JavaScript, Sixth Edition 11 Using Built-In JavaScript Classes Table 7-1 Built-in JavaScript classes
  • 12. JavaScript, Sixth Edition 12 Using Built-In JavaScript Classes (cont’d.) • Instantiating an object – Some of the built-in JavaScript objects used directly in code – Some objects require programmer to instantiate a new object – Example: Math object’s PI(π) property in a script // calculate the area of a circle based on its radius function calcCircleArea() { var r = document.getElementById("radius").value; var area = Math.PI * Math.pow(r, 2); // area is pi times ↵ radius squared return area; }
  • 13. JavaScript, Sixth Edition 13 Using Built-In JavaScript Classes (cont’d.) • Instantiating an object (cont’d.) – Can instantiate Array object using array literal • Example: var deptHeads = []; – Can instantiate empty generic object using object literal • Example: var accountsPayable = {}; • Generic object literal uses curly braces around value – Can't use object literal for Date object • Must use constructor • Example: var today = new Date();
  • 14. JavaScript, Sixth Edition 14 Using Built-In JavaScript Classes (cont’d.) • Performing garbage collection – Garbage collection • Cleaning up, or reclaiming, memory reserved by a program – Declaring a variable or instantiating a new object • Reserves memory for the variable or object – JavaScript knows when a program no longer needs a variable or object • Automatically cleans up the memory
  • 15. JavaScript, Sixth Edition 15 Using the Date, Number, and Math Classes • Three of most commonly used JavaScript classes: – Date, Number, and Math
  • 16. JavaScript, Sixth Edition 16 Manipulating the Date and Time with the Date Class • Date class – Methods and properties for manipulating the date and time – Allows use of a specific date or time element in JavaScript programs Table 7-2 Date class constructors
  • 17. JavaScript, Sixth Edition 17 Manipulating the Date and Time with the Date Class (cont’d.) • Example: – var today = new Date(); – Month and year date representation in a Date object – Stored using numbers matching actual date and year • Days of the week and months of the year – Stored using numeric representations • Starting with zero: similar to an array • Example: – var independenceDay = new Date(1776, 6, 4);
  • 18. JavaScript, Sixth Edition 18 Manipulating the Date and Time with the Date Class (cont’d.) • After creating a new Date object – Manipulate date and time in the variable using the Date class methods • Date and time in a Date object – Not updated over time like a clock – Date object contains the static (unchanging) date and time • Set at the moment the JavaScript code instantiates the object
  • 19. JavaScript, Sixth Edition 19 Table 7-3 Commonly used methods of the Date class (continues) Manipulating the Date and Time with the Date Class (cont’d.)
  • 20. JavaScript, Sixth Edition 20 Table 7-3 Commonly used methods of the Date class Manipulating the Date and Time with the Date Class (cont’d.)
  • 21. JavaScript, Sixth Edition 21 Manipulating the Date and Time with the Date Class (cont’d.) • Each portion of a Date object can be retrieved and modified using the Date object methods – Examples: var curDate = new Date(); curDate.getDate(); • Displaying the full text for days and months – Use a conditional statement to check the value returned by the getDay() or getMonth() method – Example: • if/else construct to print the full text for the day of the week returned by the getDay() method
  • 22. JavaScript, Sixth Edition 22 var today = new Date(); var curDay = today.getDay(); var weekday; if (curDay === 0) { weekday = "Sunday"; } else if (curDay === 1) { weekday = "Monday"; } else if (curDay === 2) { weekday = "Tuesday"; } else if (curDay === 3) { weekday = "Wednesday"; } else if (curDay === 4) { weekday = "Thursday"; Manipulating the Date and Time with the Date Class (cont’d.)
  • 23. JavaScript, Sixth Edition 23 var today = new Date(); var months = ["January","February","March",↵ "April","May","June",↵ "July","August","September",↵ "October","November","December"]; var curMonth = months[today.getMonth()]; Manipulating the Date and Time with the Date Class (cont’d.) • Example: include an array named months – 12 elements assigned full text names of the months
  • 24. JavaScript, Sixth Edition 24 Manipulating Numbers with the Number Class • Number class – Methods for manipulating numbers and properties containing static values • Representing some numeric limitations in the JavaScript language – Can append the name of any Number class method or property • To the name of an existing variable containing a numeric value
  • 25. JavaScript, Sixth Edition 25 Manipulating Numbers with the Number Class (cont’d.) • Using Number class methods Table 7-4 Number class methods
  • 26. JavaScript, Sixth Edition 26 Manipulating Numbers with the Number Class (cont’d.) • Using Number class methods (cont’d.) – Primary reason for using any of the “to” methods • To convert a number to a string value with a specific number of decimal places – toFixed() method • Most useful Number class method – toLocaleString() method • Converts a number to a string formatted with local numeric formatting conventions
  • 27. JavaScript, Sixth Edition 27 Manipulating Numbers with the Number Class (cont’d.) • Accessing Number class properties Table 7-5 Number class properties
  • 28. JavaScript, Sixth Edition 28 Performing Math Functions with the Math Class • Math class – Methods and properties for mathematical calculations • Cannot instantiate a Math object using a statement such as: var mathCalc = new Math(); – Use the Math object and one of its methods or properties directly in the code • Example: var curNumber = 144; var squareRoot = Math.sqrt(curNumber); // returns 12
  • 29. JavaScript, Sixth Edition 29 Table 7-6 Math class methods Performing Math Functions with the Math Class (cont’d.)
  • 30. JavaScript, Sixth Edition 30 Table 7-7 Math class properties Performing Math Functions with the Math Class (cont’d.)
  • 31. JavaScript, Sixth Edition 31 Performing Math Functions with the Math Class (cont’d.) • Example: – Use the PI property to calculate the area of a circle based on its radius • Code uses the pow() method to raise the radius value to second power, and the round() method to round the value returned to the nearest whole number var radius = 25; var area = Math.PI * Math.pow(radius, 2); var roundedArea = Math.round(area); // returns 1963
  • 32. JavaScript, Sixth Edition 32 Defining Custom JavaScript Objects • JavaScript: not a true object-oriented programming language – Cannot create classes in JavaScript – Instead, called an object-based language • Can define custom objects – Not encapsulated – Useful to replicate the same functionality an unknown number of times in a script
  • 33. JavaScript, Sixth Edition 33 Declaring Basic Custom Objects • Use the Object object – var objectName = new Object(); – var objectName = {}; • Can assign properties to the object – Append property name to the object name with a period
  • 34. JavaScript, Sixth Edition 34 Declaring Basic Custom Objects (cont'd.) • Add properties using dot syntax – Object name followed by dot followed by property name – Example: InventoryList.inventoryDate = new Date(2017, 11, 31);
  • 35. JavaScript, Sixth Edition 35 Declaring Basic Custom Objects (cont'd.) • Can assign values to the properties of an object when object first instantiated • Example: var PerformanceTickets = { customerName: "Claudia Salomon", performanceName: "Swan Lake", ticketQuantity: 2, performanceDate: new Date(2017, 6, 18, 20) };
  • 36. JavaScript, Sixth Edition 36 Declaring Sub-Objects • Value of a property can be another object – called a sub-object – Example–order object with address sub-object: var order = { orderNumber: "F5987", address: { street: "1 Main St", city: "Farmington", state: "NY", zip: "14425"
  • 37. Referring to Object Properties as Associative Arrays • Associative array – An array whose elements are referred to with an alphanumeric key instead of an index number • Can also use associative array syntax to refer to the properties of an object • With associative arrays – Can dynamically build property names at runtime JavaScript, Sixth Edition 37
  • 38. JavaScript, Sixth Edition 38 Referring to Object Properties as Associative Arrays (cont'd.) • Can use associative array syntax to refer to the properties of an object • Example: var stopLightColors = { stop: "red", caution: "yellow", go: "green" }; stopLightColors["caution"];
  • 39. JavaScript, Sixth Edition 39 Referring to Object Properties as Associative Arrays (cont'd.) • Can easily reference property names that contain numbers – Example: var order = { item1: "KJ2435J", price1: 23.95, item2: "AW23454", price2: 44.99, item3: "2346J3B", price3: 9.95 };
  • 40. JavaScript, Sixth Edition 40 Referring to Object Properties as Associative Arrays (cont'd.) • Can easily reference property names that contain numbers (cont'd.) – To create order summary: for (var i = 1; i < 4; i++) { document.getElementById("itemList").innerHTML +=↵ "<p class='item'>" + order["item" + i] + "</p>"; document.getElementById("itemList").innerHTML +=↵ "<p class='price'>" + order["price" + i] + "</p>"; };
  • 41. JavaScript, Sixth Edition 41 Referring to Object Properties as Associative Arrays (cont'd.) • Can also write generic code to add new object properties that incorporate numbers – Example—adding items to shopping cart: totalItems += 1; // increment counter of items in order currentItem = document.getElementById("itemName").innerHTML; currentPrice = document.getElementById("itemPrice").innerHTML; newItemPropertyName = "item" + totalItems; // "item4" newPricePropertyName = "price" + totalItems; // "price4" order.newItemPropertyName = currentItem; // order.item4 = (name) order.newPricePropertyName = currentPrice; // order.price4 = (price);
  • 42. JavaScript, Sixth Edition 42 Creating Methods • Object method simply a function with a name within the object • Two ways to add method to object – Provide code for method in object – Reference external function
  • 43. JavaScript, Sixth Edition 43 Creating Methods (cont'd.) • Specify method name with anonymous function as value – Example: var order = { items: {}, generateInvoice: function() { // function statements } };
  • 44. JavaScript, Sixth Edition 44 Creating Methods (cont'd.) • Specify method name with existing function as value – Example: – Reference to existing function cannot have parentheses function processOrder() { // function statements } var order = { items: {}, generateInvoice: processOrder };
  • 45. JavaScript, Sixth Edition 45 Enumerating custom object properties • Custom objects can contain dozens of properties • To execute the same statement or command block for all the properties within a custom object – Use the for/in statement – Looping statement similar to the for statement • Syntax for (variable in object) { statement(s); }
  • 46. JavaScript, Sixth Edition 46 Enumerating custom object properties (cont'd.) • for/in statement enumerates, or assigns an index to, each property in an object • Typical use: – validate properties within an object
  • 47. JavaScript, Sixth Edition 47 var item={ itemNumber: "KJ2435J", itemPrice: 23.95, itemInstock: true, itemShipDate: new Date(2017, 6, 18), }; for (prop in order) { if (order[prop] === "") { order.generateErrorMessage(); Enumerating custom object properties (cont’d.) • Example—checking for empty values:
  • 48. JavaScript, Sixth Edition 48 Deleting Properties • Use the delete operator • Syntax delete object.property • Example: delete order.itemInStock;
  • 49. JavaScript, Sixth Edition 49 Defining Constructor Functions • Constructor function – Used as the basis for a custom object – Also known as object definition • JavaScript objects – Inherit all the variables and statements of the constructor function on which they are based • All JavaScript functions – Can serve as a constructor
  • 50. JavaScript, Sixth Edition 50 Defining Constructor Functions (cont’d.) • Example: – Define a function that can serve as a constructor function function Order(number, order, payment, ship) { this.customerNumber = number; this.orderDate = order; this.paymentMethod = payment; this.shippingDate = ship; }
  • 51. JavaScript, Sixth Edition 51 Adding Methods to a Constructor Function • Can create a function to use as an object method – Refer to object properties with this reference – Example: function displayOrderInfo() { var summaryDiv = document.getElementById("summarySection"); summaryDiv.innerHTML += ("<p>Customer: " +↵ this.customerNumber + "</p>"); summaryDiv.innerHTML += ("<p>Order Date: " +↵ this.orderDate.toLocaleString()+ "</p>"); summaryDiv.innerHTML += ("<p>Payment: " +↵ this.paymentMethod + "</p>"); summaryDiv.innerHTML += ("<p>Ship Date: " +↵
  • 52. JavaScript, Sixth Edition 52 Using the prototype Property • After instantiating a new object – Can assign additional object properties • Use a period • New property only available to that specific object • prototype property – Built-in property that specifies the constructor from which an object was instantiated – When used with the name of the constructor function • Any new properties you create will also be available to the constructor function
  • 53. Using the prototype Property (cont’d.) • Object definitions can use the prototype property to extend other object definitions – Can create a new object based on an existing object JavaScript, Sixth Edition 53
  • 54. Summary • Object-oriented programming (or OOP) – The creation of reusable software objects • Reusable software objects – Called components • Object – Programming code and data treated as an individual unit or component • Objects are encapsulated • Interface represents elements required for a source program to communicate with an object JavaScript, Sixth Edition 54
  • 55. Summary (cont’d.) • Principle of information hiding • Code, methods, attributes, and other information that make up an object – Organized using classes • Instance – Object created from an existing class • An object inherits the characteristics of the class on which it is based • Date class contains methods and properties for manipulating the date and time JavaScript, Sixth Edition 55
  • 56. Summary (cont’d.) • Number class contains methods for manipulating numbers and properties • Math class contains methods and properties for performing mathematical calculations • Can define custom object – object literal • Can create template for custom objects – constructor function • this keyword refers to object that called function • prototype property specifies object's constructor JavaScript, Sixth Edition 56