Presentation is loading. Please wait.

Presentation is loading. Please wait.

Tuesday, July 28 th, 2015 Instructor: Craig Duckett Objects.

Similar presentations


Presentation on theme: "Tuesday, July 28 th, 2015 Instructor: Craig Duckett Objects."— Presentation transcript:

1 Tuesday, July 28 th, 2015 Instructor: Craig Duckett cduckett@cascadia.edu Objects

2 2 ASSIGNMENT 1 TONIGHT Due TONIGHT by MIDNIGHT (Tuesday, July 28 th ) UPLOADED TO STUDENT TRACKER IN A SINGLE.ZIP FOLDER FILE Does everyone know how to ZIP multiple files into a single folder file ?

3 3 ASSIGNMENT ANNOUNCEMENTS REMINDER: Submit via StudentTracker. If you haven't already done so, you will need to set up a StudentTracker account in order to upload your Assignment (ZIPPED up in a single file) Assignment 1 due on TONIGHT Tuesday, July 28 th, by midnight. Assignment 1 Revision due on Lecture 10, Thursday, August 6 th, by midnight. Assignment 2 due on Lecture 11, Tuesday, August 11 th, by midnight. Assignment 2 Revision due on Lecture 13, Tuesday, August 18 th, by midnight. Assignment 3 due on Lecture 14, Thursday, August 20 th, by midnight. Assignment 3 Revison due on Lecture 16, Thursday, August 27 th, by midnight.

4 4 JavaScript vs. Java Revisited…

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

6 6 Objects

7 7 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 objects like 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 objects are 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

8 8 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-like manner. This enables the programmer to take advantage of some (but not all) of the good things that come with object-orientation.

9 9 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 Objects essentially are things. Objects in JavaScript have characteristics, known as properties, and can perform actions, known as methods.

10 10 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. Objects in JavaScript (to repeat) can perform actions, known as methods, and also have characteristics, known as properties.

11 11 Object JavaScript Object

12 12 CookPrep BusserFront Desk Restaurant Dishwasher Bartender Manager Server

13 13 Defining Objects

14 14 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: var someString = new String("This is a string of characters!"); var x = someString.length // "length" is a property var y = someString.toUpperCase(); // toUpperCase() is a method

15 15 Defining Objects CONTINUED var someString = 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!"

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

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

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

19 19 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 car object 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.

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

21 21 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: var myObject = { }; This is called an object initializer or object literal. Objects can also be created with the new keyword, like so: var myObject = 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.

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

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

24 24 Objects: Constructor Function

25 25 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 car object, 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 }

26 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

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

28 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: var myCar = 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 new instance of the car object due to the value you are assigning to it. You next see that the myCar variable 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

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

30 Putting It All Together To 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; } var myCar = new car("leather","V-6","Radio with 6 CD Player"); var engineType = 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

31 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 myCar and a new one named wifesCar: function car(seats, engine, soundSystem) { this.seats= seats; this.engine = engine; this.soundSystem= soundSystem; } var myCar = new car("leather","V-6","Radio with 6 CD Player"); var wifesCar = new car("cloth", "V-4", "Radio with 1 CD Player and MP3"); var engineType = myCar.engine; var engineTypeWife = 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 wifesCar instance of the car object. 31 Constructor Function CONTINUED

32 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; } var myCar = new car("leather","V-6","Radio with 6 CD Player"); var wifesCar = new car("cloth", "V-4", "Radio with 1 CD Player and MP3"); var customEngine = myCar.engine; var customSeats = myCar.seats; var customSoundSystem = wifesCar.soundSystem; document.write("I want a car with " + customSeats + " seats. "); document.write("It also needs a "+ customEngine + " engine. "); document.write("Oh, and I would like a " + customSoundSystem + " also."); 32 Constructor Function CONTINUED

33 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; } var myCar = new car("leather","V-6","Radio with 6 CD Player"); var wifesCar = new car("cloth", "V-4", "Radio with 1 CD Player and MP3"); var customCar = new car(myCar.seats, myCar.engine, wifesCar.soundSystem); document.write("I want a car with " + customCar.seats + " seats. "); document.write("It also needs a "+ customCar.engine + " engine. "); document.write("Oh, and I would like a " + customCar.soundSystem + " also."); 33 Constructor Function CONTINUED

34 34 Objects: Object Initializers (Literals)

35 An object initializer (or object literal) is a little bit shorter than a constructor function. The following is the syntax of an object initializer: objectName = {property:value} In the preceding code, you would replace objectName with 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 value with 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 (Literals)

36 Example You can create a myCar object 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.seats would be leather. 36 Object Initializers CONTINUED

37 Example If you want the wifesCar object 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 Object Initializers CONTINUED

38 38 Objects: Adding Methods

39 In JavaScript, a method is a function that 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

40 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: 40 Methods CONTINUED function getPayment() { var thePayment = 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; }

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

42 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

43 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() { var thePayment = 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; } var myCar = new car("leather","V-6","Radio with 6 CD Player"); var wifesCar = new car("cloth","V-4","MP3 Player"); var customCar = new car(myCar.seats, myCar.engine, wifesCar.SoundSystem); 43 Methods CONTINUED

44 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: var myCarPayments = myCar.payment(); The value of the myCarPayments variable 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 myCar instance of the car object. Since the seats are "leather", thePayment is increased by 100 (if they were cloth it would have been 50). Since the engine is a "V-6", thePayment is increased by 150. Finally, since the soundSystem property has a value of "Radio with 6 CD Player", the thePayment variable is increased by 35. This gives you a payment of 250 (initial value) + 100 (leather seats) + 150 (V-6 engine) +35 (non-MP3 Player), which turns out to be 535. 44 Methods CONTINUED

45 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 Methods CONTINUED

46 function getPayment() { var thePayment = 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 1

47 var myCar = new car("leather","V-6","Radio with 6 CD Player"); var wifesCar = new car("cloth","V-4","MP3 Player"); var customCar = new car(myCar.seats, myCar.engine, wifesCar.soundSystem); var myCarPayment = myCar.payment(); var wifesCarPayment = wifesCar.payment(); var customCarPayment = customCar.payment(); 47 Example Part 2

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

49 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 (var variableName in objectName) { // JavaScript statements } 49 Object Manipulation Statements

50 Suppose you wanted to cycle through the properties of a myCar instance of a car object in 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; } var myCar = new car("leather","V-6","Radio with 6 CD Player"); for (var propName in myCar) { document.write(myCar[propName] + " "); } 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. 50 Object Manipulation Statements CONTINUED http://faculty.cascadia.edu/cduckett/bit116/Lecture_10/object_11.html

51 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 } 51 Object Manipulation Statements CONTINUED

52 Suppose you have an object named car with the properties seats, engine, and soundSystem, and an instance of the object named myCar. You could use the with statement to avoid typing myCar and the dot operator repeatedly, as in the following example: function car(seats, engine, soundSystem) { this.seats = seats; this.engine = engine; this.soundSystem = soundSystem; } var myCar = new car("leather","V-6","Radio with 6 CD Player"); with (myCar) { document.write("Seats: " + seats + " "); document.write("Engine: " + engine + " "); document.write("Sound System: " + soundSystem + " "); } 52 Object Manipulation Statements CONTINUED

53 53 Predefined JavaScript Objects

54 In JavaScript, there are many predefined objects you can use to gain access to certain properties or methods you may need. You can make your scripts even more interactive once you learn the various objects and what you can do with them. The remainder of this lecture will be covering a number of the major predefined objects. To get started we are going to look at the navigator object and history objects, and what you can do with them. Other predefined JavaScript objects we'll look at as we come upon them as the quarter progresses. 54 Predefined JavaScript Objects

55 The navigator object gives you access to various properties of the user’s browser, such as its name, version number, and more. It got its name from the Netscape Navigator browser, which preceded Mozilla/Firefox. The navigator object is part of the window object, which means you can access its properties and methods using window.navigator.property_or_method_name, but it can also be shortened to simply navigator.property_or_method_name. This is true even for direct properties or methods of the window object as well (for example, window.alert(“Hello”); could be shortened to simply alert(“Hello”); and it would still be valid). You’ll commonly see such properties and methods of the window object shortened in this way to save extra typing or to help shorten the source code. 55 The Navigator Object

56 Properties The properties of the navigator object let you find out various things about the browser the user is using. The properties of the navigator object cannot be changed, because they are set as read-only. This is so you don’t try to change the user’s browser version from 8.0 to 9.0 or something similar. Instead, you can just find out what the value of the property is and use it to allow your scripts to do different things for different browsers. 56 The Navigator Object CONTINUED http://www.w3schools.com/jsref/obj_navigator.asp

57 57

58 Now that you know the properties of the navigator object, you can begin to use them in your scripts. The following sections take a look at some of the more useful properties in more detail. The appCode Property This property holds the value of the application code name of the browser, which is often something like Mozilla. Other than writing it to the screen or sending an alert to the user, you don’t have much use for it at this time. The following code shows how to send an alert to the viewer to tell him or her the appCodeName of the browser being used to view the page: alert("You are using " + navigator.appCodeName); Notice that you use the object name followed by the dot operator and then the property name, just like you did when you created your own objects. This is how you are able to access the properties of the navigator object. Note that with this property, most every browser will return "Mozilla", which was used as the code name for an early version of Netscape Navigator. 58 The Navigator Object CONTINUED

59 The appName Property This property allows you to find out which type of browser the user is using to browse the page. If the browser is Firefox, the value of this property will be Netscape. If the browser is Internet Explorer, then the value of this property will be Microsoft Internet Explorer. Other browsers will have corresponding values. If you need to know the value for a particular browser, you can create a script to alert the value of this property, place the script inside script tags on a Web page, and then view the page in that browser. You will then be alerted to the value of the property for that browser. The following code shows how the alert can be coded: alert("You have " + navigator.appName); 59 The Navigator Object CONTINUED http://www.w3schools.com/jsref/prop_nav_appname.asp

60 The appName Property CONTINUED Suppose you want to send the viewer an alert based on your opinion of the browser being used. You could use the navigator.appName property to create an if/else block and send the appropriate comment to the viewer based on the browser type: switch (navigator.appName) { case "Netscape" : alert("Firefox is cool."); break; case "Microsoft Internet Explorer" : alert("IE is CENSORED."); break; case "Opera" : alert("Opera is interesting."); break; default : alert("What browser is this?"); } Hi There! Wuzzup? 60 The Navigator Object CONTINUED

61 The appVersion Property This property has a value of the version number of the browser and some additional information. For example, in Firefox 27 for Windows 7, you might see the following text as the value of this property: 5.0 (Windows) This can be beneficial when you use techniques that should only be executed in browser versions above a certain level. Note, though, that browsers return various results for this property, as the value returned for Internet Explorer 11 on Windows 7 shown here: 5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2;.NET CLR 2.0.50727;.NET CLR 3.5.30729;.NET CLR 3.0.30729;.NET4.0C;.NET4.0E; Media Center PC 6.0; InfoPath.3; Creative AutoUpdate v1.40.03; rv:11.0) like Gecko You must use care when using this property as you will need to know what various browsers return to make the best use of the information. 61 The Navigator Object CONTINUED http://www.w3schools.com/jsref/prop_nav_appversion.asp

62 The cookieEnabled Property This property returns a Boolean value of true if cookies are enabled in the browser, and returns a Boolean value of false if cookies are not enabled in the browser. The onLine Property This property returns a Boolean value of true if the viewer’s system is not in global offline mode (see http://msdn.microsoft.com/en-us/library/aa768170(VS.85).aspx for details on this), and returns a Boolean value of false if the system is in global offline mode.http://msdn.microsoft.com/en-us/library/aa768170(VS.85).aspx The platform Property This property holds the value of the type of machine for which the browser was created. For example, on a Windows 7 machine, the value would be Win32. There are different values for various types of machines. If you want to let the viewer know the machine type being used, you could send an alert with this property: alert("Your machine is a "+navigator.platform + " machine."); While not very useful here, the property could be used to redirect viewers to an appropriate page based on their machine type. 62 The Navigator Object CONTINUED http://www.w3schools.com/jsref/prop_nav_cookieenabled.asp http://www.w3schools.com/jsref/prop_nav_online.asp http://www.w3schools.com/jsref/prop_nav_platform.asp

63 The plugins Property This array holds the values of all the plugins installed in the viewer’s browser. The userAgent Property This property gives you another long string of information about the browser. This string is the user agent header for the browser. For instance, in Firefox 27 for Windows 7, you might see the following string: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0 It is pretty similar to the text you saw for the navigator.appVersion property, but with a little more information. Now that you know about the properties of the navigator object, you are ready to look at the methods of the object. 63 The Navigator Object CONTINUED http://www.w3schools.com/jsref/prop_nav_useragent.asp

64 The navigator object also has a number of methods you can use to perform various tasks. 64 The Navigator Object: Methods

65 The javaEnabled() Method This method returns a Boolean value of true if the viewer has Java enabled in the browser; otherwise, it returns false. The javaEnabled() method could be useful if you want to display a Java applet to the viewer, but only if the viewer has Java enabled in the browser. For now, you will just see how to send the viewer an alert, as an example. This way you don’t need to mess with any Java syntax yet. The following code sends one alert if the viewer has Java enabled and sends another if the viewer does not have Java enabled: var hasJava = navigator.javaEnabled() if (hasJava == true) { alert("Cool, you have Java!"); } else { alert("Java disabled? You cannot see my Java Applet!"); } This tests the value returned by the navigator.javaEnabled() method and gives the user the correct alert. Again, this is more useful if you have a Java applet that you want to use someplace on the page. 65 The Navigator Object: Methods CONTINUED

66 The history object, which is also part of the window object, provides information on the browser history of the current window. Property The history object has only one property, named length (in Firefox, a few more are available, but they do not work with web content). This property returns the number of pages in the session history of the browser for the current window, which includes the currently loaded page. It could be used in a manner similar to this: alert("Your current window has viewed "+ history.length +" pages!") This simply sends an alert to the viewer to say how many pages have been visited in the current browser window session. 66 The History Object

67 Methods There are three methods of the history object: 67 The History Object CONTINUED

68 Methods CONTINUED The back() Method The back() method sends the browser to the last page visited in the history list before the current page, which is like using the browser’s “back” button. To use it, you simply call the method in your script where desired. Thus, if you wanted your own “back” button made from a form button, you could use something similar to the following code. var bb = document.getElementById("backButton"); bb.onclick = function() { history.back(); }; 68 The History Object CONTINUED

69 Methods CONTINUED The forward() Method The forward() method sends the browser to the page visited in the history list after the current page, which is like using the browser’s “forward” button. To use it, you simply call the method in your script where desired. Using this, you could update your previous script to add a “forward” button as well. var bb = document.getElementById("backButton"); var fb = document.getElementById("forwardButton"); bb.onclick = function() { history.back(); }; fb.onclick = function() { history.forward(); }; 69 The History Object CONTINUED

70 Methods CONTINUED The go() Method The go() method takes in an integer as a parameter. The integer can be a negative number to go back in the history list or a positive number to move forward in the history list. For instance, the following code would go back two pages in the window’s history: history.go(-2); The following code would go forward three pages in the history list: history.go(3); As with the other two methods, if the page the viewer is attempting to access does not exist (for example, something like history.go(15) may not exist in the window’s history), then the method will simply do nothing. 70 The History Object CONTINUED

71 71 Objects: Summary Slides

72 In JavaScript, an object can be created in a couple of ways. A primary way to create an object is by the new keyword, like so: var myObject = new Object; Objects can also be created by using two curly braces, like so: var myObject = {}; This is called an object literal. 72 What Does an Object Look Like?

73 In JavaScript, an object can be created in a couple of ways. A primary way to create an object is by the new keyword, like so: var myObject = new Object; Objects can also be created by using two curly braces, like so: var myObject = {}; This is called an object literal. 73 What Does an Object Look Like?

74 You can also nest objects, as shown in this example: var guitar = { "color": "red", "strings": { "number": 6, "smallGauge": 9, "largeGauge": 42 }, "type": "electric" }; In this example, a nested object is created and contains properties about the strings of the guitar, including the number of strings and their gauge. 74 Object Properties CONTINUED

75 Properties are accessed by using dot notation or by including the property name in brackets. Here’s an example of dot notation: guitar.color; //red guitar.strings.smallGauge; // 9 Here’s an example of property name in brackets: guitar["color"]; //red guitar["strings"]["smallGauge"] //9 It’s usually preferable from a readability standpoint to use dot notation when possible, but that’s really a matter of developer preference and his-or-her coding standard. 75 Object Properties CONTINUED

76 In addition to having properties, many objects do things. With my assistance, the guitar plays individual notes on a given string as well as chords with multiple strings. In JavaScript, you can create a function, store it as a property, and then call or invoke that function. These functions are essentially just like the functions you learned about earlier, except they’re called methods when used with objects. Methods are declared, they can accept arguments just like functions, and they can return values. For the purposes of this class, methods are just like functions that are added or attached to an object. 76 Object Methods

77 Building on the guitar object, here’s a method to play a string: var guitar = { "color": "red", "strings": 6, "type": "electric", "playString": function (stringName) { var playIt = "I played the " + stringName + " string"; return playIt; } //end function playString }; In this example a method called playString is declared and accepts one argument. That variable, called stringName, is used to indicate the string to play on the guitar and is then used to create a message indicating that the guitar string was played. 77 Object Methods CONTINUED

78 If you preferred, you could have created this method later then add it to the guitar object by using dot notation. Assuming that the guitar object has been created already, adding the method looks like this: guitar.playString = function(stringName) { var playIt = "I played the " + stringName + " string"; return playIt; } 78 Object Methods CONTINUED

79 One of the more powerful aspects of object-oriented programming is the use of the this keyword. The this keyword provides self-referential access to an object’s properties and methods. You can use this to perform advanced operations within an object’s methods. For example, using this, you can get and set an object’s properties in a consistent manner (sometimes known as getters and setters). 79 the this Keyword

80 Here's an example with the guitar object again: var guitar = { "color": "red", "strings": 6, "type": "electric", "playString": function (stringName) { var playIt = "I played the " + stringName + " string"; return playIt; }, "getColor": function() { return this.color; }, "setColor": function(colorName) { this.color = colorName; } }; alert(guitar.getColor()); // This alert will show 'red' guitar.setColor("blue"); // This method changes the color to "blue" alert(guitar.getColor()); // This alert will show 'blue' 80 the this Keyword CONTINUED

81 The two additions to the guitar object are the getter and setter methods, getColor() and setColor(), respectively. The getColor() method looks like this: "getColor": function() { return this.color; } This method merely returns the color property as it is currently set. The setColor() method looks like this: "setColor": function(colorName) { this.color = colorName; } This method sets the color as it is passed into the method call. 81 the this Keyword CONTINUED

82 82 Objects Links JavaScript Objects (W3Schools) JavaScript Objects Intro to Objects (W3Schools) Intro to Objects Back to Basics: JavaScript Object Syntax (SitePoint) Back to Basics: JavaScript Object Syntax Working with Objects (MDN) Working with Objects Dynamic Objects in JavaScript Dynamic Objects in JavaScript The Object.Create() Method (HTML Goodies) The Object.Create() Method Creating Custom Objects in JavaScript (JavaScript Kit) Creating Custom Objects in JavaScript Objects: JavaScript Tutorial (JavaScript.Info) Objects: JavaScript Tutorial The Basics of Object-Oriented JavaScript (Tutsplus) The Basics of Object-Oriented JavaScript JavaScript Object Basics (YouTube Video) JavaScript Object Basics

83 83 Please begin working on the LECTURE 7 In-Class Exercises. When you have completed your ICE, call the Instructor over to verify your work. If you have questions about your work, please call over the Instructor to clarify. Once you have completed your ICEs, you are free to go for the day. If you don't finish your ICEs by the end of class, you will still get full credit for actively doing the work, but it is greatly recommended you finish any outstanding ICEs outside of class.


Download ppt "Tuesday, July 28 th, 2015 Instructor: Craig Duckett Objects."

Similar presentations


Ads by Google