1 / 21

JAVASCRIPT

JAVASCRIPT. Session 4. Overview. Introduction, Data Types, Operators and Statements JavaScript Objects, Forms, Functions The Browser, The DOM, Dynamic pages, Debugging JavaScript and Custom Object creation, Storage XML - JSON, Introduction to Ajax. Prototyping.

Download Presentation

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. JAVASCRIPT Session 4

  2. Overview • Introduction, Data Types, Operators and Statements • JavaScript Objects, Forms, Functions • The Browser, The DOM, Dynamic pages, Debugging • JavaScript and Custom Object creation, Storage • XML - JSON, Introduction to Ajax

  3. Prototyping • In languages such as Java or C++, we sometimes create classes as a sort of “extension” of another. In order to do so, we define the class in such a way that it inherits the functionality of the higher-level object and we then override whatever functionality we don’t want. • JavaScript is a bit different. Like Java and C++, JavaScript does provide a top-level Object class, thereby allowing you to create new objects should you want to do so. However instead of true inheritance, we will extend an object via a “prototype”. • Here is an example of extending the ‘Number’ object by adding a method that accepts two arguments and returns the sum: Number.prototype.add=function(val1, val2) {return val1+val2}; • We can now invoke this add() method using any Number object.

  4. Prototyping <html> <head> <title>Prototype Example</title> <script type="text/javascript"> function windows() { Number.prototype.add=function(val1, val2) { return val1+val2 }; var num = new Number(); var result = num.add(4, 5); alert("The result = " + result); } </script> </head> <body onload="windows()"> <p>H1</p> <noscript> <p>I'm able to be displayed</p> </noscript> </body> </html> See: prototyping.htm

  5. Prototyping • One caveat is that if you create a prototype ‘add’ and the next version of JavaScript Number object has an add method, your method will be overridden.

  6. Custom Objects Creating custom objects is a major part of object-oriented programming. However it is very possible that some of you may have not yet encountered it. To go into a full introduction would take a fair amount of time. For now, we will suffice with a brief overview of the techniques used to do so in JavaScript. However, you will not be responsible for doing so on your own in this part of the course. Creating a new object: Tune Will contain 2 properties and 2 methods. Properties: • title - String • performedBy – Array (of strings) Methods: • addPerformer(pName) //adds pName to the array ‘performedBy’ • listPerformers() //outputs all of the performers

  7. Custom Objects – The Constructor InJavaScript, the way we create new Objects is via a special function called a ‘constructor’. This function will list the properties and methods that we wish to include in our new Object. In this case, we want to create two properties (title, performedBy) and two methods (addPerformer, listPerformers). We do so as follows: var Tune = function(t) { var title = t; var performedBy = new Array(); this.addPerformer = function(performer) { //code for 'addPerformer()' goes here... } this.listPerformers = function() { //code for 'listPerformers()' goes here }

  8. Custom Objects var Tune = function(title) { this.title = title; var performedBy = new Array(); this.addPerformer = function(performer) { var i = performedBy.length; performedBy[i] = performer; } this.listPerformers = function() { var singers = ""; for(var i=0;i<performedBy.length;i++) { singers += performedBy[i] + " "; } return singers; } } // Now it’s time to test our new ‘Tune’ object function initTune() { var song = new Tune("Judy Blue Eyes"); song.addPerformer("Crosby"); song.addPerformer("Stills"); song.addPerformer("Nash"); document.writeln("Song is : " + song.title); document.writeln("Performed by: " + song.listPerformers()); } window.onload = initTune(); Note that unlike the way things are typically done in languages such as Java, in JS, many consider it good form to implement the object’s methods inside the object’s constructor. See: custom_object.htm

  9. Creating a new instance of your object • Recall that when a function defining a new object is written, it becomes the object constructor. • This special constructor function invoked when the ‘new’ keyword is used: Tune song1 = new Tune("Eye of the Tiger");

  10. Creating a custom object using prototyping <html> <head> <title>Object Example</title> <script type="text/javascript"> function Tune(theTitle) { title = theTitle; } function printTitle() { document.writeln(this.title + "<br />"); } function initTune() { Tune.prototype.print = printTitle; var oneTune = new Tune("One Title"); oneTune.print(); var anotherTune = new Tune("Another Title"); anotherTune.print(); } window.onload(initTune()); </script> </head> <body> <p>some content</p> </body> </html> We can also use prototyping to create the methods for our custom object. Note that even though these object methods are intended to be used only for the object, the functions are global. Many programmers find using this way of doing things (i.e. prototyping) to be quick and easy – and it has become popular to do so. However the downside is that in creating global functions, you may end up overriding some other function – or that another programmer will override your function!

  11. Ajax - Prototype.js • One popular Ajax library is Prototype.js. It makes extensive use of the prototype property to expand functionality on the Array object as well as Object itself. This presents a bit of a problem since the extensive use of prototyping means that this library may not “play nice” with other libraries.

  12. Dealing with errors via ‘Exception Handling’ • An error in your code - even a relatively innocuous one – can sometimes cause the entire script and page to fail. For this reason, programmers recognize the need to invest a certain amount of time and code to ensure that errors are handled appropriately. However, there is a tremendous range of effectiveness and efficiency in the many error handling techniques that are out there. • One of the preferred techniques for error checking and handling is through the use of ‘exception handling’. Most commonly, exception handling is done through the use of “try-catch-finally” blocks. • Beginning with JavaScript 1.5, the use of try...catch...finally was incorporated into the JavaScript language.

  13. try-catch-finally Template • Inside your catch block you can investigate the 'exception' object that was generated when the error occurred. • The 'finally ' block is optional. This block is included in situations where some operation(s) must be carried out regardless of whether or not an error was generated. try { //code that might generate errors here } catch (exception) { //code to catch the exception } finally { //code that is always executed }

  14. Exception Types • Six error types are implemented in JavaScript 1.5 • EvalError - Raised by eval when it’s used incorrectly • RangeError - Raised when the numeric value exceeds its range • ReferenceError - Raised when an invalid reference is used • SyntaxError - Raised when there is invalid syntax used • TypeError - Raised when a variable is not if the type expected • URIError - Raised when encodeURI() or decodeURI() is used incorrectly • There is an operator called ‘instanceof’ that can be very useful in exception handling. It can tell you whether a certain error is one of the known types listed above.

  15. Exception Handling Example var arr = null; try { console.log( arr[4] ); //will generate a TypeError exception } catch (exception) { if (exception instanceof EvalError) console.log("An EvalError exception was generated"); else if (exception instanceof RangeError) console.log("A RangeError exception was generated"); else if (exception instanceof TypeError) console.log("A TypeError exception was generated"); else //handle all remaining unspecified exceptions console.log("An exception was generated with the message: " + exception.message); } finally { console.log("Inside the 'finally' block"); } Note: Some of you may be used to separate catch clauses. However, the version showing here, though more verbose, conforms to the ECMASpecification. See: exceptions.htm

  16. Storage • Originally JavaScript was not intended to be used to create large and complex applications, or to communicate independently with a server. The primary way to store any information on the client was through cookies. • However, once security issues became an increasing concern, businesses (and individuals) have been in the habit of turning off cookie support. • If not abused, cookies are very helpful for both developer and end-user. • Improved methods and standards for storing data on the client are increasingly being considered and developed.

  17. Same-Origin Security policy • Ensures that there is no communication via script between pages that have different domains, protocols or ports. • Protects against snooping from one domain on another domain. • Even within the pages residing in same domain there are limitations. For example, if your domain is: http://www.somecompany.com , then none of the following sites would be allowed to communicate with each other via JavaScript: • http://othercompany.com  Different domain altogether • https://www.somecompany.com  Different protocol (https) • http://www.somecompany.com:8080  Different port (default is port 80) • http://other.somecompany.com  Different host • There are techniques for allowing pages within the same domain to communicate provided that the server is configured to allow it.

  18. Cookies • They are a mechanism of the HTTP server (not innate to JavaScript). However, they are accessible in JavaScript via the document object. • Small key/value pairs associated with an expiration date and a domain/path. • To Create: • Provide a cookie name, or key and associated value • A date when it expires • A path associated with the cookie • Optional fourth parameter indicating security level • Example: document.cookie="cookieName=cookieValue; expires=date; path=path"; • To Read: var cookie = document.cookie; • This will return a single long string. This string will then need to be parsed in order to determine the various keys and values. • E.g. use the String object's 'split()' method to split based on semicolons.

  19. Forms <form id="someForm"...> var entireForm = document.getElementById("someForm"); • Intercepting the form before submitting to the server for processing (e.g. for purposes of validation): • Capture the event using inline event handler • Capture the event using traditional event handler • Use the EventListener.attachEvent option • A key aspect is the ability to cancel the event if the form validation fails for whatever reason. For now, we will confine our discussion to retrieving information from the form.

  20. Retrieving info from a form We typically make frequent use of the getElementById() function to return the values from form elements. Recall that any time we retrieve a value from a form element, it always comes back as a string. Therefore, if we wish to treat the value as a quantitiy (Number), then we must use either parseInt() / parseFloat() functions or the Number object. Text Validation: We can do form validation such as ensuring that the user has entered required information (or has not entered invalid information) prior to submitting the form. In the example below, we will use the 'onblur' event to examine the 'zip code' form field the moment they click away from that text box. See: museum_admission_ipd.htm

  21. End of Session 4 • Next Session • Introduction to Ajax

More Related