1 / 72

OOP in Javascript

OOP in Javascript. Objectives. Study object-oriented programming Work with the Date , Number , and Math objects Define custom JavaScript objects. The Hallmarks of OOP. What are they?. The Hallmarks of OOP. Encapsulation Inheritance Polymorphism Code reuse. Reusing Software Objects.

friedmanl
Download Presentation

OOP in Javascript

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. OOP in Javascript

  2. Objectives • Study object-oriented programming • Work with the Date, Number, and Math objects • Define custom JavaScript objects JavaScript, Fifth Edition

  3. The Hallmarks of OOP • What are they?

  4. The Hallmarks of OOP • Encapsulation • Inheritance • Polymorphism • Code reuse

  5. 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, Fifth Edition

  6. Reusing Software Objects (cont’d.) • Objects range from simple controls to entire programs • Popular object-oriented programming languages • C++, Java, Visual Basic JavaScript, Fifth 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, Fifth Edition

  8. What Is Encapsulation? (cont’d.) • Advantages of encapsulation • Reduces code complexity • Prevents accidental bugs and stealing of code • Programming object and its public interface • Compare to a handheld calculator JavaScript, Fifth Edition

  9. What Is Encapsulation? (cont’d.) • Document object is encapsulated (black box) • write() and writeln() methods • Part of the interface JavaScript uses to communicate with the Document object Figure 6-3 Conceptual example of the Document object black box JavaScript, Fifth Edition

  10. Understanding Classes • Classes • 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

  11. Introduction to Object-Oriented Programming • Object-oriented programming • Allows reuse of code without having to copy or recreate it Class Definition object object object object object

  12. Understanding Classes • Javascript access objects that already exist (thanks to the browser software. • Objects in the browser object model (BOM) • Part of the Web browser • No need to instantiate them to use them • Example: the document object

  13. Built-in javascript classes • Come with the language • Allow us to instantiate and use common types of objects • Not editable

  14. Using Built-In JavaScript Classes Table 6-1 Built-in JavaScript classes

  15. Using Built-In JavaScript Classes (cont’d.) • Instantiating an object • Some of the built-in JavaScript objects used directly in code • Example: Math object’s PI(π) property in a script <script type="text/javascript"> // The following statement prints 3.141592653589793 document.write("The value of pi is " + Math.PI); </script>

  16. Using Built-In JavaScript Classes (cont’d.) • Some objects require programmer to instantiate a new object ( new …) • Instantiating an object (cont’d.) • Array object requires programmer to instantiate a new object before use • Example: • vardeptHeads = new Array();

  17. 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

  18. Using the Date, Number, and Math Classes • Three most commonly used JavaScript classes: • Date, Number, and Math

  19. 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 6-2 Date class constructors

  20. 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: • varindependenceDay = new Date(1776, 6, 4);

  21. 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

  22. Manipulating the Date and Time with the Date Class (cont’d.) Table 6-3 Commonly used methods of the Date class (continues)

  23. Manipulating the Date and Time with the Date Class (cont’d.) Table 6-3 Commonly used methods of the Date class

  24. 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: varcurDate = 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() function

  25. Manipulating the Date and Time with the Date Class (cont’d.) <script type="text/javascript"> var today = new Date(); varcurDay = today.getDay(); if (curDay == 0) document.write("Today is Sunday."); else if (curDay == 1) document.write("Today is Monday."); else if (curDay == 2) document.write("Today is Tuesday."); else if (curDay == 3) document.write("Today is Wednesday."); else if (curDay == 4) document.write("Today is Thursday."); else if (curDay == 5) document.write("Today is Friday."); else if (curDay == 6) document.write("Today is Saturday."); </script>

  26. Manipulating the Date and Time with the Date Class (cont’d.) Figure 6-4 Output of a script with a getDay() method

  27. 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 <script type="text/javascript"> var today = new Date(); var months = new Array(); months[0] = "January"; months[1] = "February"; months[2] = "March"; months[3] = "April"; months[4] = "May"; months[5] = "June"; months[6] = "July"; months[7] = "August"; months[8] = "September"; months[9] = "October"; months[10] = "November"; months[11] = "December"; var curMonth = months[today.getMonth()]; document.write("<p>The current month is " + curMonth + ".</p>"); </script>

  28. Manipulating the Date and Time with the Date Class (cont’d.) Figure 6-5 Output of a script with a getMonth() method

  29. 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

  30. Manipulating Numbers with the Number Class (cont’d.) • Using Number class methods Table 6-4 Number class methods

  31. 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 • Converts IE and Firefox default number of decimal places

  32. Manipulating Numbers with the Number Class (cont’d.) • Accessing Number class properties Table 6-5 Number class properties

  33. 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: varmathCalc = new Math() • Use the Math object and one of its methods or properties directly in the code • Example: varcurNumber = 144; squareRoot = Math.sqrt(curNumber); // returns '12' document.write("The square root of " + curNumber + " is " + squareRoot);

  34. Performing Math Functions with the Math Class (cont’d.) Table 6-6 Math class methods

  35. Performing Math Functions with the Math Class (cont’d.) Table 6-7 Math class properties

  36. 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 round() method to round the value returned to the nearest whole number var radius = 25; var area = Math.round(Math.PI * radius * radius); // return 1963 document.write("A circle with a radius of " + radius + " has an area of " + area);

  37. 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

  38. Declaring Basic Custom Objects • Use the Objectobject • varobjectName = new Object(); • varobjectName = {}; • Can assign properties to the object • Append property name to the object name with a period • Custom objects created as described in this section • Limited to containing only properties • Objects most useful when they contain both properties and methods

  39. 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

  40. Defining Constructor Functions (cont’d.) • Example: • Define a function that can serve as a constructor function functionConcertTickets(customer, concert, tickets, eventDate) { ... } • Example: • To instantiate an instance of a ConcertTickets object varnewOrder = newConcertTickets();

  41. Working with Object Properties • Adding properties • Add a statement to the function body that uses the this keyword with the following syntax: • this.property_name = value; • this keyword refers to the object that calls the constructor function

  42. Working with Object Properties (cont’d.) • Adding properties (cont’d.) • Example: • functionConcertTickets(customer, event, quantity, eventDate) { • this.customerName = customer; // customer name • this.concertName = event; // event name • this.ticketQuantity = quantity; // number of tickets • this.concertDate = eventDate; // concert date • }

  43. Working with Object Properties (cont’d.) • Adding properties (cont’d.) • Can assign values to the properties of an object when object first instantiated • Example: varticketOrder = new ConcertTickets("Don Gosselin", "Jimmy Buffett", 2, new Date(2010, 6, 18, 20)); document.write("<h1>Ticket Order</h1>"); document.write("<p>Customer: " + ticketOrder.customerName); document.write("<br />Concert: " + ticketOrder.concertName); document.write("<br />Quantity: " + ticketOrder.ticketQuantity); document.write("<br />Date: " + ticketOrder.concertDate.toLocaleString() + "</p>");

  44. Exercise • Write a function defining a Planet’s attributes • As in your solar system animation program

  45. Example function Planet(diameter, smajor, sminor, angle, name, color, increment) { }

  46. Example function Planet(diameter, smajor, sminor, angle, name, color, increment) { this.x= ; // x coordinate this.y = ; // y coordinate this.diameter = ; // diameter this.smajor = ; // length of semimajor axis this.sminor = ; // length of semiminor axis this.angle = ; // angle this.name = ; // name this.color = ; // color this.increment = ; // angle increment }

  47. Example function Planet(diameter, smajor, sminor, angle, name, color, increment) { this.x = xcenter + smajor; // x coordinate this.y = ycenter + sminor; // y coordinate this.diameter = diameter; // diameter this.smajor = smajor; // length of semimajor axis this.sminor = sminor; // length of semiminor axis this.angle = angle; // angle this.name = name; // name this.color = color; // color this.increment = increment; // angle increment }

  48. Exercise • Use your Planet function to do the following: • “instantiate” a Planet object with specific attributes • Use the Planet object’s attributes to draw the Planet

  49. Instantiation sun = new Planet(25, 0, 0, 0, "Sun", "yellow", 0); earth = new Planet(10, 150, 50, 0, "Earth", "blue", 5);

  50. function drawPlanet(orb) { // draw planet c.beginPath(); c.fillStyle = orb.color; orb.x = xcenter + orb.smajor * Math.cos(Math.PI/ 180 * orb.angle); orb.y = ycenter - orb.sminor * Math.sin(Math.PI/ 180 * orb.angle); c.arc(orb.x, orb.y, orb.diameter, Math.PI*2, false); // draw orb c.fill(); c.closePath(); orb.angle += orb.increment; }

More Related