Introducing JavaScript - Computer Science@IUPUI

Download Report

Transcript Introducing JavaScript - Computer Science@IUPUI

Introducing JavaScript
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Goals
By the end of this lecture you should …
• Be able to describe the differences among object
methods, object properties and events
• Be able to describe how we declare, initialize and
type JavaScript variables
• Be able to describe how we assign values to
variables
• Be able to describe how to convert values to
different types
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
What is JavaScript?
• JavaScript is a “Client-side” scripting
language.
• JavaScript is usually housed in a Webpage.
• JavaScript's syntax is similar to C and
Java.
• JavaScript deals with objects.
• JAVASCRIPT IS NOT THE SAME AS JAVA!
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
What is an Object?
• An object is a unique entity in a script
and/or web page. An object has
object properties, object methods and
can react to events in that object’s
environment.
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Object Properties
• A property is a characteristic that
describes an object. It is similar to an
adjective in grammar. Properties are
given values (Hair Color is a property;
its value might be brown or red).
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Object Methods
• A method is something an object can do.
It is similar to a verb in grammar.
Sometimes we need to give methods
descriptive words that tell it how to work.
These descriptive words are called
arguments (Running might be a method of
the “human object”; an argument for
running might be the speed at which to
run).
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Events
• An event is something in an object’s
environment to which that object can
react. For the human object, a fire alarm
is an event; Humans react to a fire alarm
using a method – exiting the building.
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Examples of JavaScript Objects
• Examples of Common JavaScript Objects:
–
–
–
–
–
–
–
A web browser’s window
A string of characters
An integer number
Text in a web page
A menu in a web page
An image
A path to an image saved in memory
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Notes about Syntax
• Spaces do not matter to the computer (but
they do improve readability for the
programmer).
• Non-structure lines end with a semi-colon  ;
• Lines that introduce a structure (like loops or if
structures) begins with a left curly brace  {
• Structures end with a right curly brace  }
• It's a good idea to add non-executable
comments to your code.
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
JavaScript Comments
• Comments are non-executable lines of code that are
used to describe, in English, what is going on in a
section of code.
• Comments in any language are offset from other
code using a special, reserved character
• Comments in JavaScript can be single-line
comments (offset with two forward-slashes  //)
• Comments in JavaScript can also be multi-line
comments (offset beginning with /* and ending with
*/)
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Comment Example
// This is a single-line comment
// These
// are also
// single line comments.
/* This is a
multi-line comment */
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Documentation Comments
• Give the user general information about the
program
• Generally found near the beginning of a script:
/* TITLE: Hello World, v 0.1
* AUTHOR: Bob Molnar (RSM)
* CREATED: 03.17.2002
* LAST MODIFIED: 03.19.2002
* LAST MODIFIED BY: RSM
* PURPOSE: The purpose of this program …
* MODIFICATION HISTORY: …
*/
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Code Comments
• Explain, in English, what’s going on in the
code
• Used to clarify code
• Usually found near variable declarations
and near structures
//String variable to store the user’s name
var userName = “”; //also a valid comment
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Introducing JavaScript Variables
• Objects are represented by variables.
• Variables are virtual containers that hold
information.
• The value of a variable can change with
changes in a program.
• Different types of variables serve different
purposes.
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Typing Variables
• Different variables serve specialized purposes,
based on what they hold:
– Primitive Types (natively understood by JavaScript)
•
•
•
•
String
Float (a.k.a “Real”)
Integer
Boolean (TRUE or FALSE)
– Objects
• Why do we type variables? Conservation of
resources!
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Creating a Variable
• Declare & name the variable
• Initialize the variable (give it an initial
value)
• Type the variable (tell the computer how
the variable is going to be used)
• We can use a Constructor method to
create variables.
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Constructor Methods
• JavaScript has a library of "blueprints"
available to it that define the nature of
some objects.
• To access those "blueprints" and create
new primitives & objects from them, we
can use constructor methods. Think of
constructor methods as a way of building
a new object from an existing blueprint.
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Creating a Variable
1
2
3
var userName = new String(“Dilbert”);
What's going on?
1. The reserved word "var" tells JavaScript to
allocate some space in memory for a variable.
2. We give a label to that variable, giving it the
name userName.
3. The "=" means "gets the value off" in
programming. It does NOT mean "equals."
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Creating a Variable
4
5
var userName = new String(“Dilbert”);
4. The reserved word "new" is called an instance
operator and it tells JavaScript to expect that we'll be
creating a new instance of object from an existing
"blueprint", in this case, from the String blueprint.
5. We use the constructor method String() to copy the
string blueprint to our userName variable.
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Creating a Variable
6
var userName = new String(“Dilbert”);
6. The String() method allows us to supply an optional
initial value for our new string. If we choose to, we
need to supply a value that is of string-type. This is
called variable initialization. Notice the word "Dilbert"
is in quotations? The quotations are a way of
identifying the word as a string. When we give a
variable its first value, we also type the variable.
JavaScript is an implicitly typed language.
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Creating Variables for Primitives
• For any of JavaScript's primitive data types
(strings, integers, floats, Booleans), you can
create a variable without calling on the
constructor:
var userName = "Dilbert";
• Although this is syntactically correct, I want you
to use constructor methods in N341. Why? Since
other, more formal, languages (like Java)
demand constructors, I want you to get used to
the habit of using them here in JavaScript.
Practice makes perfect!
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Changing a Variable Value
• Changes in the program sometimes require
changes in a variable’s value.
• To change a variable's value, we use variable
assignment.
• Assignment replaces any previous variable
values with a new value.
• Since JavaScript doesn't retain a variable's
previous value during assignment, we say
assignment is a destructive operation.
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Assignment in JavaScript
userName = “Dogbert”;
Variable Name
New Value
“Gets the value of”
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Variable Assignment: Input
• We can make our programs more interesting by
interacting we our user via modal input
• Modal input is a way to ask a user a question
and then put their answer into a variable
• In JavaScript, this is usually done using the
prompt method.
• Prompt is a method of the Window object
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Variable Assignment: Input
userName = window.prompt(“Your name?”, “”);
Variable Name
Method:
Creates a box
to ask a
question
Method Arguments:
Question to be asked &
default value
Assignment Operator:
“Gets the value of”
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Quick Note on the Dot Operator
• Did you notice in the previous example that the
window object connected to its prompt method
using a period? The period is called a dot
operator.
• A dot operator is a way of showing how things
are connected to objects. In the previous
example, the dot operator connected the
window object to its prompt method.
• We’ll learn more about the dot operator later …
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Converting Variable Types
• Sometimes, it’s necessary to convert from one
type of a variable value to another (for example,
converting string input to an integer value).
• Converting values in JavaScript is usually done
using any one of two parse functions or the
toString() method:
– parseInt() – converts a variable value to an integer.
– parseFloat() – converts a variable value to a float.
– NUMBER.toString() – converts a variable value to a string.
• NOTE: When using modal windows, all input
from the user comes back as a STRING type!
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Conversion Example
var myInteger = new Number(0);
myInteger = window.prompt(“Give me an integer”, 0);
myInteger = parseInt(myInteger);
var myString = new String("");
myString = myInteger.toString();
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Output in JavaScript
• One way to output information in
JavaScript is to use the alert method of
the window object
• The alert method takes either string
literals or variable names as its argument:
window.alert(“Hello World!”);
var myMessage = new String(“Hello World!”);
window.alert (myMessage);
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Arithmetic Operators
Operator
Name
Example
+
Addition
a=b+c
-
Subtraction
a=b-c
/
Division
a=b/c
*
Multiplication
a=b*c
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Arithmetic Operators
Operator
Name
Example
%
Modulus
a=b%c
+
Unary
Addition
a = +b
-
Unary
Subtraction
a = -b
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Arithmetic Operators
Operator
++
--
Name
Example
Pre-Increment
a = ++b
Post-Increment
a = b++
Pre-Decrement
a = --b
Post-Decrement
a = b--
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Assignment Operators
Operator
Name
Example
Equivalency
=
Assignment
x = y;
x = "Hi";
*None
+=
Add by Value
x += 5;
x = x + 5;
-=
Subtract
by Value
x -= 5;
x = x – 5;
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Assignment Operators
Operator
Name
Example
Equivalency
/=
Divide
by Value
x /= 5;
x = x / 5;
*=
Multiply
by Value
x *= 5;
x = x * 5;
&=
Modulus
by Value
x %= 5;
x = x % 5;
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
String Concatenation
• A way to join variable values with other
variable values or with string literals
• You should avoid long single-line
concatenations (use multi-line instead).
• Use either the “+” operator or the “+=”
operator.
• Hint: Keep spacing within quotes!
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
String Concatenation
window.alert(“Hello ” + userName + “!”);
or using a multi-line concatenation (preferred) …
response = “Hello, ”;
response += userName;
response += “! It’s nice to meet you!”);
window.alert(response);
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Operator Precedence
Order
Description
1
Parenthesis (Work from inside
out)
2
Dot Operator
3
Instance Operator
4
Multiplication, Division, Modulus
5
Addition, Subtraction,
Concatenation
6
Assignment
Operator
()
.
new
* / %
+ -
= += -=
*= /= %=
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science
Questions?
CSCI N341: Client-Side Web Programming
Copyright ©2004  Department of Computer & Information Science