
Javascript Programming Variables, Functions, Objects, and Events Brad Rippe [email protected] Agenda Questions FYI - New Edition of the book in the bookstore Lecture 2 – Variables, Functions and Objects Assignment 2 Quiz 1 Hand in Assignment 1 Javascript Basics <script></script> Interpreted code Basic instructions are called “statements” alert(‘This is a statement); var studentNum = 30; // statement too Sequential order of execution Predefined functionality executed by javascript engine in the browser 1 Reserved Words abstract else instanceof switch boolean enum int synchronized break export interface this byte extends long throw case false native throws catch final new transient char finally null true class float package try const for private typeof continue function protected var debugger goto public void default if return volatile delete implements short while do import static with double in super Variables Must be declared with the “var” reserved word var name = “Brad”; var total = 35.00; var isResourceAvailable = false; var assignNum = 1, assignDes = “description”; Variable names must start with a alpha character, “_” or “$” Variable names should be descriptive $savingsAccount savingsAccount Variable Naming Conventions Start with a lower case letter for the first word An consecutive words are capitalized var name = “Brad”; // single word vars var firstName = “Brad”; var lastName = “Rippe”; 2 Try Using Variables <script language=“javascript1.5”> var name = “brad”;// your name var lastName = “rippe”; document.write(name); document.writeln(lastName); // notice there is a write and a // writeln function </script> Example 1 Variables… <script language="javascript1.5"> var num1 = 5; var num2 = 2; // add two numbers alert(num1+num2); // multiple two numbers alert(num1*num2); </script> Example 2 - Try Functions Functions are away of organizing statements into one callable statement Declared before called Usually accomplish one task, i.e., printName(); validateForm(); checkBrowser(); swapImages(); 3 Defining Functions function nameOfFunction(parameters) { statements; } function is a javascript reserved word. It tells the javascript engine you are defining a function. nameOfFunction is an arbitrary name, an identifier which can be referred to later or elsewhere in the html file. Parameters are a list of variables that are available to the function. {} denote the beginning and ending of the function definition. Assume the rest of the slides are from within <script></script> tags. Example Function without Parameters list function printName() { document.write(“<b>”); document.writeln(“Joe”); document.write(“</b>”); document.write(“<b>”); document.writeln(“Steve”); document.write(“</b>”); document.write(“<b>”); document.writeln(“Mary”); document.write(“</b>”); } printName(); Example 3 Problems: Example Function without Parameters List Repetitive code Hard to follow More work than needed can be accomplished with parameter passing 4 Parameter Passing Example Function passing parameters function printName(name) { document.write(“<b>”); document.writeln(name); document.write(“</b>”); } printName(“Joe”); printName(“Steve”); printName(“Mary”); Example 4 - Try Parameter Passing printName(“Joe”); printName(“Steve”); printName(“Mary”); Note the code above passes values “Joe”, “Steve”, and “Mary” The value of the variable name is changed with each call. 5 Variable Scope Variables only exist in the block of code that they are defined. References to variables outside they’re visible scope causes an error. Variables out of scope function printName(name) { document.write(“<b>”); document.writeln(name); document.write(“</b>”); } printName(“Joe”); printName(“Steve”); printName(“Mary”); printName(name); Global Variables var someOtherName = “My Name”; Global Scope function printName(name) { Local Scope document.write(“<b>”); document.writeln(name); document.write(“</b>”); } printName(“Joe”); printName(“Steve”); printName(“Mary”); printName(someOtherName); 6 Functions that return value utility functions: calculateTax() validateEmail() computeMedian() average_numbers(a, b, c) – Note?? Statement that invoked the method (function) will receive a value. Functions that return value function printName(name) { document.write(“<b>”); document.writeln(name); document.write(“</b>”); return “printed”; } Example 5 - Try Functions that return value var name = printName("Joe"); document.writeln("<br>"); document.writeln(name); name = printName("Steve"); document.writeln("<br>") document.writeln(name); name = printName("Mary”); document.writeln("<br>") document.writeln(name); Example 5 7 Returning Integer Value function average_numbers(a, b, c) { var sum_of_numbers = a + b + c; var result = sum_of_numbers / 3; return result; } Example 6, 7, 8 Problems average_numbers(a, b, c) Use the convention Function names should start with a lower-case letter and any consecutive words should be capitalized. Parameters should be descriptive a : num1 b : num2 C : num3 Javascript Objects Used to store like data Usually model real world entities Person Book Product CD Similar to a function definition/declaration Need to use the keyword new when instantiating Objects 8 How do we define an Object? function Book(title, author, callNumber) { this.title = title; this.author = author; this.callNumber = callNumber; } … Book javascript = new Book(“Javascript”, “Don Gosselin”, “js2345”); document.writeln(javascript.title); Example 9 Javascript Objects Array – creates new array objects Boolean – creates new Boolean objects Date Retrieves and manipulates dates and times Error Returns run-time error information Function – creates new function objects Global – represents the javascript built-in method Math – contains methods and properties for performing mathematical calculations Number – contains methods and properties for manipulating numbers Object – provides common functionality to all built-in Javascript objects RegExp – contains properties for finding and replacing in text strings String – contains methods and properties for manipulating text strings Object functions function Book(title, author, callNumber) { this.title = title; this.author = author; this.callNumber = callNumber; // we use printBook, although we could call it anything // to reference the printBook function this.printBook = printBook; // the “()” is left off because “printBook()” denotes a function call } function printBook() { document.writeln("<b>Title: </b>"); document.writeln(this.title); document.writeln("<br><b>Author: </b>"); document.writeln(this.author); document.writeln("<br><b>Call Number: </b>"); document.writeln(this.callNumber); } Example 10 9 Calling Object methods // Notice construction of the object is the same // Now to print the object, we simply // call the printBook(); var book = new Book("Javascript", "Don Gosselin", "js2345"); // use dot notation to call object methods (functions) book.printBook(); Object Key Points Attributes (variables) characteristics Methods (functions) behavior JavaScript supports several types of objects. They are as follows: User-defined objects defined by the programmer Core or built-in objects, such as Date, String, and Number Browser and Document objects Skip Object Inheritance Page 62 & 63 10 Events An event is a specific circumstance that is monitored by Javascript. Examples Mouse clicks Mouse over Loads Blur Focus Mouse out Select Unload Allows us to interact with the users Manipulate the document or react to the user’s actions HTML Forms Allow users to send data to a process. <form action="URL to server program" method="post"> The body of the form goes here, including input devices for filling out the form </form> HTML Form Elements Button Select Text File Textarea Hidden Password Submit Checkbox Image Radio Reset 11 Example Event Handling <form name=“jsForm” action=“” method=“get”> <input type=“button” name=“btn” value=“Click Me” onclick=“alert(this.value);”> </form> Example Event Handling <input type=“button” name=“btn” value=“Click Me” onclick=“alert(‘Ouch!’);”> Example Error <input type=“button” name=“btn” value=“Click Me” onclick=“alert(“Ouch!”);”> Remember HTML is NOT case sensitive, so onClick, onCLICK, OnClick are the same. 12 Getting User Data Prompt the user for input prompt(message); var someInput = prompt(‘Type anything’); alert(‘You typed ‘+someInput); Example 12 Overriding the browser’s event handling <script language=“javascript1.5”> function warnUser() { return confirm(‘This link is only…’); } </script> … <body> … <a href=“http://www.fullcoll.edu” onClick=“return warnUser();”> Fullerton College</a> Example 13 MouseOver and Out <a href="http://www.fullcoll.edu" onMouseOver="document.bgColor='red'" onMouseOut="document.bgColor='green'"> Fullerton College</a> 13 Assignment 2 Questions??? 14.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages14 Page
-
File Size-