1 / 82

BIT116: Scripting Lecture 12

BIT116: Scripting Lecture 12. Instructor: Craig Duckett cduckett@cascadia.edu. Wednesday, February 19 th , 2014. Supplement to the Reading : Murach's JavaScript and DOM Scripting Chapter 11: How to Create and Use Objects pp. 356-383 . Objects. ASSIGNMENT 1 REVISON.

bernie
Download Presentation

BIT116: Scripting Lecture 12

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. BIT116: ScriptingLecture 12 Instructor: Craig Duckett cduckett@cascadia.edu Wednesday, February 19th, 2014 Supplement to the Reading: Murach's JavaScript and DOM Scripting Chapter 11: How to Create and Use Objectspp. 356-383 Objects

  2. ASSIGNMENT 1 REVISON DueTONIGHTbyMIDNIGHT This is your last chanceto get points for Assignment 1 if you have not turned anything in yet. I will be lockingAssignment 1 Revision in StudentTracker at 6:00 am tomorrowmorning so no more submissions can be made after that time. If you have not turned in an Assignment 1/Assignment 1 Revision by the time this is locked you will not receive any points for this first assignment! A word to the wise is sufficient.

  3. MID-TERM Post-Mortem

  4. JavaScript vs. Java Remember that is Java we worked with classes, the fuzzy "idea" of attributes and actions that couldn't do anything until you created or instantiated an object from a class (much in the way we created an object called karel from the Robot class). JavaScript, although object-oriented, however is class-less! If you want to create an object that has properties and can do something, you need to create an instance of an object not from a class, but from a prototype…and it's up to you as the developer to set up the prototype! In other words, except for the pre-defined objects in JavaScript (e.g., like Date or Array) you need to set up the prototype (or structure) of an object before you can create or instantiate a new object from it. Today's lecture will demonstrate why this is and how it is done.

  5. Objects

  6. Objects Since JavaScript is an object-based language, you need to look at objects to understand what they are and how you can use them. In JavaScript, the predefined objectslike Date, Function, and Array are very useful; however, to use them effectively, it is a good idea to learn how objects work in general and how to create your own objects if you need them. This lecture begins by defining what objectsare and how objects can be useful to you in your scripts. You will then discover how to create and name your own objects that you can use in your code. Finally, we'll have a look at the properties and methods of the predefined navigator and history objects. http://www.w3schools.com/js/js_objects.asp

  7. Defining Objects To begin using JavaScript objects, you need to find out what they are and how they can be useful to you in your scripts. First take a look at what JavaScript objects are. Objects are part of the programming paradigm known as object-oriented programming, sometimes shortened to OOP. JavaScript is not a full object-oriented language, but it behaves in a largely object-likemanner. This enables the programmer to take advantage of some (but not all) of the good things that come with object-orientation.

  8. Defining Objects CONTINUED • What is an Object? • In JavaScript most everything (except undefined and null) are objects. • Booleans can be objects or primitive data treated as objects • Numbers can be objects or primitive data treated as objects • Strings are also objects or primitive data treated as objects • Dates are always objects • Maths and Regular Expressions are always objects • Arrays are always objects • Even functions are always objects • Objectsessentially are things. • Objects in JavaScript have characteristics, known as properties, and can perform actions, known as methods.

  9. Defining Objects CONTINUED Looking outside of computer programming for an example, a lamp is an object. As I’m creating this slide, I have a lamp on the desk next to me (actually two, located on a raised shelf setting behind my monitor). The lamp has certain characteristics, its type (like whether or not it is a standing lamp or a desk lamp), its size, its color, the number of bulbs it holds, whether it’s turned on with a button or a pull string, and so on. The lamp next to me today is a type known as a "banker's lamp", a desk lamp with a brushed brass base, rollover glass shade of emerald green, and single pull string. The lamp can, along with my assistance, do things like turn on or off, or adjust the angle of the shade to direct or defuse the light. It can therefore be said that this lamp object has certain properties and can perform certain actions. Objectsin JavaScript (to repeat) can perform actions, known as methods, and also have characteristics, known as properties.

  10. JavaScript Object Object Object Object Object Object Object Object

  11. Restaurant Manager Cook Prep Dishwasher Server Busser Front Desk Bartender

  12. Defining Objects

  13. Defining Objects CONTINUED • An Object is a collection of characteristics (properties) and actions or functions (methods). • Object Syntax • The syntax for using an object is: • object. property • object.method() • A string is an object in JavaScript and has several properties and methods: • varsomeString = new String("This is a string of characters!"); • var x = someString.length// "length" is a property • var y = someString.toUpperCase(); // toUpperCase() is a method

  14. Defining Objects CONTINUED • varsomeString = new String("This is a string of characters!"); • var x = someString.length// "length" is a property • var y = someString.toUpperCase(); // toUpperCase() is a method • If this code is executed, someString is a variable with the value of "This is a string of characters!". • The x variable is set to the length of someString, in this case 32. Length is a property of the string object. If you count the characters (letters, spaces, punctuation) between the quotes you will see it adds up to 32. • The toUpperCase() method coverts all of the alphabetical characters in the string to upper case:"THIS IS A STRING OF CHARACTERS!"

  15. Defining Objects CONTINUED JavaScript has several objects built into the language, like String, Math, Date, and Array. The Math object is a collection of methods and properties for performing mathematical operations like min(), max(), sin(), cos(), etc. The Date object is a collection of methods for working with dates and time. The Array object allows programmers to create collections of data, and so on.

  16. Defining Objects CONTINUED • The new Operator / Keyword • Objects cannot simply be typed into your JavaScript programs. They must first be created. • We use the "new" operator or keyword to create a new instance of an object. • To put it another way, the new operator creates a functional copy of an existing object and assigns the name you want to it. • The generic syntax is: • myObject = new Object(); • Since objects are made up of actions of functions (methods) and characteristics (properties), the newly created myObject in this case has all the same methods and properties of the original Object.

  17. Our "old friend" the Document Object Model (DOM) which we'll talk about again in more depth next week

  18. Why Objects Are Useful Objects are useful because they give you another way to organize things within a script. Rather than having a bunch of similar variables that are out there on their own, you can group them together under an object. For example, let's say we have a carobject and create variables to represent the features of the car, then you can begin to see how this type of grouping works. You could create variables with the names seats, engine, and soundSystem (we won't demonstrate creating the car object until a bit later, so for now assume that the car object exists and that it has the properties of seats, engine, and soundSystem). Since these properties are variables, they can have values. The question is, how do you access these properties to get their values? In JavaScript, you access object properties through the use of the dot operator.

  19. Why Objects Are Useful CONTINUED • For instance, if you wanted the value of the seats property of the car, you could access it with the following line: • var x = car.seats; • Don’t let the assigning of the value of the seats property to a variable (x) be confusing. What you want to see here is the car.seats part of the code. • The name of the object is written first, then the property you want to access is connected to it on the right using the dot operator. • The seats property doesn’t currently have a value (since we haven’t actually created the car object yet). We will see how to give it and other properties values when we begin creating objects in the next slides.

  20. Creating Objects • In JavaScript, an object can be created in a number of ways. • A primary way to create an object is by using two curly braces, like so: • varmyObject = { }; • This is called an object initializeror object literal. • Objects can also be created with the new keyword, like so: • varmyObject = new Object; • In practice, I’ve seen both types of object creation used about equally in JavaScript programs, and so as this class progresses I may sometimes create an object using new and other times as a literal.

  21. Creating Objects CONTINUED Naming Objects As with variables and functions, there are certain rules you have to follow when naming your objects in JavaScript. They are essentially the same rules you follow for naming variables and functions, so I will just discuss them briefly here since you have been through this twice already. Case Sensitivity As with previous naming, object names are case sensitive. Thus, an object named car would be different from an object named Car, CAR, or caR. In order to access the right object, you have to be sure to use the proper case when you use it in the script; otherwise, you will receive an error such as “Car is not an object” when you try to run the script. Avoid Reserved Words/Objects The other thing to remember when naming your own objects is that you cannot use a JavaScript reserved word. Trying to make an object named switch could give you problems because that word is used for the JavaScript switch statement.

  22. Creating Objects CONTINUED Object Structure There are two ways to create objects in JavaScript: by using a constructor function or by using an object initializer. First, we will learn how to use constructor functions to create objects. This will be followed by a brief discussion of how to use the object initializers.

  23. Objects: Constructor Function

  24. Constructor Function • A constructor function allows you to build an object using the same basic syntax as a regular function. The only difference is the code you place inside of the function and how you access its contents. • For example, to create a carobject, you would create a constructor function named car() and then add your properties within the function. • The following example shows an outline of the car() function: • function car() { • //properties go here • }

  25. Constructor Function CONTINUED • To complete the preceding function, you need to add your properties to the function. • Recall that we wanted to create an object named car with the properties of seats, engine, and soundSystem. • The following code shows how this is done: • function car(seats, engine, soundSystem) { • this.seats = seats; • this.engine = engine; • this.soundSystem = soundSystem; • }

  26. Constructor Function CONTINUED • function car(seats, engine, soundSystem) { • this.seats = seats; • this.engine = engine; • this.soundSystem = soundSystem; • } • In this code, on the first line, you see that the function takes three parameters, which is the number of properties you want the car object to have. • The next thing you see is that the values of the parameters are assigned to the properties you want the car object to have; however, there is also the this keyword (remember, just like in Java). • The keyword this in JavaScript is used to represent the current object being used, or “this object,” so to speak.

  27. Constructor Function CONTINUED • Once you have the object’s properties set with the constructor function, you need to create what is called an instance of the object in order to use it, because a constructor function creates only the structure of an object, not a usable instance of an object. To create an instance of an object, you use the JavaScript keyword: new. • The use of the new keyword to create an instance of your car object is shown in the following code: • varmyCar = new car("leather","V-6","Radio with 6 CD Player"); • The first thing you see is that you are creating a new variable named myCar. This variable will be a newinstance of the car object due to the value you are assigning to it. • You next see that the myCarvariable is assigned the result of the car constructor function, with a twist. • In front of the call to the car function is the new keyword, which makes sure you are creating a new instance of the constructor function object. • Next, you see that the car function is called with values sent as parameters. These are the values you want to use for this instance of the car object. Given the order, you are saying that you want the seats to be leather, the engine to be V-6, and the soundSystem to be a Radio with 6 CD Player.

  28. Constructor Function CONTINUED • function car(seats, engine, soundSystem) { • this.seats = seats; • this.engine = engine; • this.soundSystem = soundSystem; • } • varmyCar = new car("leather","V-6","Radio with 6 CD Player"); • You can now access the myCarinstance of the car object. • If you want to know what type of engine the myCarhas, you can access it with the dot operator: • varengineType = myCar.engine; • This assigns the value of the engine property of the myCarinstance of the car object to the variableengineType. Since you sent V-6 as the engine parameter to the constructor function, the engineTypevariable is assigned a value of V-6.

  29. Constructor Function CONTINUED • Putting It All TogetherTo help you visualize this process, it’s time to put all these parts together so that you can see how it works. The following code combines all the code of the previous examples to make things easier to see • function car(seats, engine, soundSystem) { • this.seats = seats; • this.engine = engine; • this.soundSystem = soundSystem; • } • varmyCar = new car("leather","V-6","Radio with 6 CD Player"); • varengineType = myCar.engine; • Now you can see the constructor function, the creation of an instance of the car object, and the assignment of one of the properties of the object to a variable. When the myCar instance of the car object is set, it gets the values of leather for the property myCar.seats, V-6 for the property myCar.engine, and Radio with 6 CD Player for the property myCar.soundSystem.

  30. Constructor Function CONTINUED • In order to see how an instance of an object works, you need to add another instance of the car object to your code. The following code uses two instances of the car object, one named myCarand a new one named wifesCar: • function car(seats, engine, soundSystem) { • this.seats = seats; • this.engine = engine; • this.soundSystem = soundSystem; • } • varmyCar = new car("leather","V-6","Radio with 6 CD Player"); • varwifesCar = new car("cloth", "V-4", "Radio with 1 CD Player and MP3"); • varengineType = myCar.engine; • varengineTypeWife = wifesCar.engine; • Notice how the new instance of the object uses the same constructor function, but with different values. You also have a new variable named engineTypeWife, which is given the value of the engine property of the wifesCarinstance of the car object.

  31. Constructor Function CONTINUED • By assigning the property values of the different instances of the car object to variables, you could now write out the features you would like to have in a custom car that combines features from each type of car. • For example, take a look at the following code, which writes out the features you might like in a custom car: • function car(seats,engine,soundSystem) { • this.seats = seats; • this.engine = engine; • this.soundSystem = soundSystem; • } • varmyCar = new car("leather","V-6","Radio with 6 CD Player"); • varwifesCar = new car("cloth", "V-4", "Radio with 1 CD Player and MP3"); • varcustomEngine = myCar.engine; • varcustomSeats = myCar.seats; • varcustomSoundSystem = wifesCar.soundSystem; • document.write("I want a car with " + customSeats + " seats.<br />"); • document.write("It also needs a "+ customEngine + " engine.<br />"); • document.write("Oh, and I would like a " + customSoundSystem + " also.");

  32. Constructor Function CONTINUED • Here's another take of it, but creating a new car object called customCar from the mix-and-match pieces: • function car(seats,engine,soundSystem) { • this.seats = seats; • this.engine = engine; • this.soundSystem = soundSystem; • } • varmyCar = new car("leather","V-6","Radio with 6 CD Player"); • varwifesCar = new car("cloth", "V-4", "Radio with 1 CD Player and MP3"); • varcustomCar = new car(myCar.seats, myCar.engine, wifesCar.soundSystem); • document.write("I want a car with " + customCar.seats + " seats.<br />"); • document.write("It also needs a "+ customCar.engine + " engine.<br />"); • document.write("Oh, and I would like a " + customCar.soundSystem + " also.");

  33. Objects: Object Initializers (Literals)

  34. Object Initializers (Literals) • An object initializer (or object literal) is a little bit shorter than a constructor function. • The following is the syntaxof an object initializer: • objectName = {property:value} • In the preceding code, you would replace objectNamewith the name you want to give your object; replace property with the name you want to use for a property of the object; and replace valuewith the value of the property that precedes it. • You can add more properties and values by separating each with a comma. • An object created with the initializer function is already an instance of the object, so you can just use the properties without the need to create a new instance of the object.

  35. Object Initializers CONTINUED • Example • You can create a myCarobject by using the initializer method. • You want the object name to be myCar, and you will have three sets of properties and values. • The following code shows how to create the object by using the object initializer method: • myCar = {seats:"leather", engine:"V-6", soundSystem:"Radio with 6 CD Player"} • Since there is no need to create an instance of the object, you can use its properties just as you did before, and assign them to variables or write them to the page. • For instance, the property of myCar.seatswould be leather .

  36. Object Initializers CONTINUED Example If you want the wifesCarobject back as well, you can use another initializer, as shown in the following example code: myCar = {seats:"leather", engine:"V-6", soundSystem:"Radio with 6 CD Player"} wifesCar = {seats:"cloth", engine:"V-4", soundSystem:"Radio with 1 CD Player and MP3"}

  37. Objects: Adding Methods

  38. Methods In JavaScript, a method is a functionthat is part of an object. The function called can perform various tasks that you might want to execute with the properties of the object.

  39. Methods CONTINUED Consider the car object that we created with a constructor function earlier in the lecture. We might want to have functions to make a calculation of some sort, like a payment. If we wanted to add a function for that object that would calculate the monthly payments on the various types (instances) of cars that we sent to it, we could create a function like the one on the right: • function getPayment() { • varthePayment = 250; • if(this.seats == "leather") { • thePayment += 100; • } • else { • thePayment += 50; • } • if(this.engine == "V-6") { • thePayment += 150; • } • else { • thePayment += 75; • } • if(this.soundSystem== "MP3 Player") { • thePpayment += 10; • } • else { • thePayment += 35; • }

  40. Methods CONTINUED Well, the previous function is really long. It can be shortened by using the conditional operator for each if/else statement here: • function getPayment() { • varthePayment = 250; • thePayment+= (this.seats == "leather") ? 100 : 50; • thePayment+= (this.engine == "V-6") ? 150 : 75; • thePayment+= (this.soundSystem== "MP3 Player") ? 10 : 35; • return thePayment; • }

  41. Methods CONTINUED • After you have defined the function, you need to assign it to your object within your object constructor function. • Using your trusty car object constructor function, you would assign it as shown in the following code: • function car(seats, engine, soundSystem) { • this.seats = seats; • this.engine = engine; • this.soundSystem = soundSystem; • this.payment = getPayment; // <-- Notice no parentheses used! • } • Notice that this example defines a method named payment that calls the getPayment() function from outside the constructor function. • Also notice that when the function is called here, the parentheses are not used on the end of the function call. • This is how your outside function becomes a method of the object (by assigning it the function rather than the result of the function).

  42. Methods CONTINUED • In order to call the payment() method of the object, you need an instance of the car object. If you add the three instances you made earlier, you will be able to do some things with your new method. So, add those instances to the code you already have: • function getPayment() { • varthePayment = 250; • thePayment+= (this.seats == "leather") ? 100 : 50; • thePayment+= (this.engine == "V-6") ? 150 : 75; • thePayment+= (this.soundSystem== "MP3 Player") ? 10 : 35; • return thePpayment; • } • function car(seats, engine, soundSystem) { • this.seats = seats; • this.engine = engine; • this.soundSystem = soundSystem; • this.payment = getPayment; • } • varmyCar = new car("leather","V-6","Radio with 6 CD Player"); • varwifesCar = new car("cloth","V-4","MP3 Player"); • varcustomCar = new car(myCar.seats, myCar.engine, wifesCar.SoundSystem);

  43. Methods CONTINUED • Now you have the function that is used to create the payment() method of the car object, the creation of the payment() method within the car object constructor function, and three instances of the car object. • To find the monthly payments for myCar, you would call the payment() method using the following syntax: • varmyCarPayments = myCar.payment(); • The value of the myCarPaymentsvariable will be the value returned from the payment() method, which is what is returned from the getPayment() function when run with the values used for the myCarinstance of the carobject. • Since the seats are "leather", thePaymentis increased by 100(if they were cloth it would have been 50). • Since the engine is a "V-6", thePaymentis increased by 150. • Finally, since the soundSystem property has a value of "Radio with 6 CD Player", the thePaymentvariable is increased by 35. • This gives you a payment of 250 (initial value) + 100 (leatherseats) + 150 (V-6engine) +35 (non-MP3 Player), which turns out to be 535.

  44. Methods CONTINUED Using the payment() method, you could now write a script to display the payment amount for each type of car in the browser so the viewer can decide what type of car to buy. You would just expand on your previous code to include in the body of the page some document.write() commands that use the values returned from the payment() method. See the example spread across the next three slides to see the whole thing put together:

  45. Example Part 1 • function getPayment() { • varthePayment = 250; • thePayment += (this.seats == "leather") ? 100 : 50; • thePayment += (this.engine == "V-6") ? 150 : 75; • thePayment += (this.soundSystem == "MP3 Player") ? 10 : 35; • return thePayment; • } • function car(seats, engine, soundSystem) { • this.seats = seats; • this.engine = engine; • this.soundSystem = soundSystem; • this.payment = getPayment; • }

  46. Example Part 2 • varmyCar = new car("leather","V-6","Radio with 6 CD Player"); • varwifesCar = new car("cloth","V-4","MP3 Player"); • varcustomCar = new car(myCar.seats, myCar.engine, wifesCar.soundSystem); • varmyCarPayment= myCar.payment(); • varwifesCarPayment= wifesCar.payment(); • varcustomCarPayment = customCar.payment();

  47. Example Part 3 • document.write("<h2>The information on the cars you requested:</h2>"); • document.write("<strong>My Car: </strong>"); • document.write(myCar.seats + ", " + myCar.engine + ", " + myCar.soundSystem); • document.write("<br>"); • document.write("<strong>Payments:</strong> $" + myCarPayment); • document.write("<p>"); • document.write("<strong >My Wife's Car: </strong>"); • document.write(wifesCar.seats + ", " + wifesCar.engine + ", " + wifesCar.soundSystem); • document.write("<br>"); • document.write("<strong>Payments:</strong> $" + wifesCarPayment); • document.write("</p>"); • document.write("<p>"); • document.write("<strong>My Dream Car: </strong>"); • document.write(customCar.seats + ", " + customCar.engine + ", " ); • document.write(customCar.soundSystem); • document.write("<br>"); • document.write("<strong>Payments:</strong> $" + customCarPayment); • document.write("</p>"); http://faculty.cascadia.edu/cduckett/bit116/Lecture_12/object_10.html

  48. Object Manipulation Statements • JavaScript allows you to use the for-in loop to help you manipulate objects and the with statement to access particular objects more easily. • The for-in Loop • The for-in loop allows you to cycle through the properties of an object to display them or to manipulate their values. • The following code shows the structure of a for-in loop: • for(varvariableNameinobjectName) { • // JavaScript statements • }

  49. Object Manipulation Statements CONTINUED • Suppose you wanted to cycle through the properties of a myCarinstance of a carobjectin order to display the values of each property on the page. The for-in loop allows you to do this without the need to type each property name, as in this code: • function car(seats, engine, soundSystem) { • this.seats = seats; • this.engine = engine; • this.soundSystem = soundSystem; • } • varmyCar = new car("leather","V-6","Radio with 6 CD Player"); • for (varpropNamein myCar) { • document.write(myCar[propName] + "<br />"); • } • You will notice that the myCar[propName] part of the script is unfamiliar. The for-in loop uses an array to store the property values, which calls for this syntax. http://faculty.cascadia.edu/cduckett/bit116/Lecture_12/object_11.html

  50. Object Manipulation Statements CONTINUED • The with Statement • The with statement allows you to access or manipulate the properties and methods of an object more easily if you plan to use a large number of statements that use the object. • For instance, if you want to write a number of statements about an object named car on a web page, you might grow weary of typing the object name (car), the dot operator, and then the property name. • The with statement allows you to leave off the object name and the dot operator for statements inside the with block, so that you only need to type the property names to access the properties you need. • The following code shows the structure of a with statement: • with (object) { • //JavaScript statements • }

More Related