[Go to site: main page, start]

0% found this document useful (0 votes)
3 views25 pages

JavaScript Core

This document is a tutorial on JavaScript core language syntax aimed at developers familiar with Java and XHTML, focusing on its use in web browsers and Ajax development. It covers topics such as embedding JavaScript in HTML, basic syntax, variables, operators, conditionals, loops, arrays, and string manipulation. Additionally, it provides references for further learning and tools like Firebug for debugging JavaScript code.

Uploaded by

Tseng Sean
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views25 pages

JavaScript Core

This document is a tutorial on JavaScript core language syntax aimed at developers familiar with Java and XHTML, focusing on its use in web browsers and Ajax development. It covers topics such as embedding JavaScript in HTML, basic syntax, variables, operators, conditionals, loops, arrays, and string manipulation. Additionally, it provides references for further learning and tools like Firebug for debugging JavaScript code.

Uploaded by

Tseng Sean
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

© 2008 Marty Hall

JavaScript:
A Crash Course
Part I: Core Language Syntax
Originals of Slides and Source Code for Examples:
[Link]
Customized Java EE Training: [Link]
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

© 2008 Marty Hall

For live Ajax & GWT training, see training


courses at [Link]
Taught by the author of Core Servlets and JSP, More
Servlets and JSP, and this tutorial. Available at
public venues, or customized versions can be held
on-site at your organization.
• Courses developed and taught by Marty Hall
– Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topics
Customized Java EE Training: [Link]
• Courses developed and taught by [Link] experts (edited by Marty)
Servlets, –JSP, Struts,
Spring, JSF/MyFaces/Facelets,
Hibernate, EJB3, Ruby/Rails Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Contact hall@coreservlets com for details
Topics in This Section
• Overview
• JavaScript references
• Embedding in browser
• Basic syntax
• Strings and regular expressions
• Functions
• Objects

4 Java EE training: [Link]

© 2008 Marty Hall

Intro

Customized Java EE Training: [Link]


Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Overview
• Goals
– Aimed at developers that already know Java
– Aimed at use of JavaScript in a Web browser
• Especially main capabilities for Ajax developers
– Not a complete reference
• Prerequisites
– Familiarity with XHTML.
• Since goal is use of JavaScript for Ajax, pages will use
XHTML syntax.
– Familiarity with Java
• Will focus on major differences from Java
– Other tutorials
• Separate tutorials on Java, XHTML, CSS, and many Ajax-
related topics can be found at [Link]
6 Java EE training: [Link]

Firebug
• Tutorial assumes you have Firebug
– Firefox environment for executing and debugging JavaScript,
tracing Ajax HTTP calls, exploring DOM, viewing CSS, and more
– Indispensible Ajax and JavaScript tool
• Quick summary
– Download from [Link]
– Invoke with F12
– Disable by default
• Right click on green Firebug arrow at bottom right
• Choose "Disable Firebug"
• Right click on Firebug icon again
• Choose "Allowed Sites"
• Enter localhost plus your main deployment sites
• On any site, you can still hit F12 and enable Firebug on that site
(temporarily or permanently)
• For more details
– See "Ajax Development Tools" in [Link] Ajax tutorial
7 Java EE training: [Link]
References
• Books
– JavaScript the Definitive Guide by David Flanagan
– Pro JavaScript Techniques by John Resig
• Online References
– JavaScript tutorial
• [Link]
– JavaScript API references (all builtin objects)
• [Link]
• [Link]
• [Link]
• [Link]
– HTML DOM reference (with JavaScript Examples)
• [Link]
– Official ECMAScript specification
• [Link]
[Link]
8 Java EE training: [Link]

9 Java EE training: [Link]


© 2008 Marty Hall

Embedding
JavaScript in HTML

Customized Java EE Training: [Link]


Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

Loading Scripts
• script with src
• <script src="[Link]" type="text/javascript"></script>
– Purpose
• To define functions, objects, and variables.
• Functions will later be triggered by buttons, other user
events, inline script tags with body content, etc.
• script with body content
• <script type="text/javascript">JavaScript code</script>
– Purpose
• To directly invoke code that will run as page loads
– E.g., to output HTML content built by JavaScript
• Don't use this approach for defining functions or for doing
things that could be done in external files.
– Slower (no browser caching) and less reusable
11 Java EE training: [Link]
Example ([Link])
function getMessage() {
var amount = [Link]([Link]() * 100000);
var message =
"You won $" + amount + "!\n" +
"To collect your winnings, send your credit card\n" +
"and bank details to oil-minister@[Link].";
return(message);
"alert" pops up dialog box
}

function showWinnings1() {
alert(getMessage());
} "[Link]" inserts text into page at current location

function showWinnings2() {
[Link]("<h1><blink>" + getMessage() +
"</blink></h1>");
}
12 Java EE training: [Link]

Example ([Link])
<!DOCTYPE ...><html xmlns="[Link]
<head><title>Loading Scripts</title>
...
Loads script from previous page
<script src="./scripts/[Link]"
type="text/javascript"></script>
</head>
<body>
Calls showWinnings1 when user presses
... button. Puts result in dialog box.
<input type="button" value="How Much Did You Win?"
> ...
<script type="text/javascript">showWinnings2()</script>
...
</body></html> Calls showWinnings2 when page is loaded in
browser. Puts result at this location in page.

13 Java EE training: [Link]


Example (Results)

14 Java EE training: [Link]

Loading Scripts: Special Cases


• Internet Explorer bug
– Scripts with src fail to load if you use <script.../>.
• You must use <script src="..." ...></script>
• XHTML: Scripts with body content
– It is an error if the body of the script contains special
XML characters such as & or <
– E.g. <script...>if (a<b) { this(); } else { that(); }</script>
– So, use CDATA section unless body content is simple
and clearly has no special characters
• <script type="text/javascript"><![CDATA[
JavaScript Code
]]></script>

15 Java EE training: [Link]


© 2008 Marty Hall

Basic Syntax

Customized Java EE Training: [Link]


Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

Variables
• Introduce with "var"
– For global variables (!) and local variables.
– No "var" for function arguments
• You do not declare types
– Some people say JavaScript is "untyped" language, but
really it is "dynamically typed" language
– JavaScript is very liberal about converting types
• There are only two scopes
– Global scope
• Be very careful with this when using Ajax. Can cause race
conditions.
– Function (lexical) scope
17
– There is not block scope as in Java
Java EE training: [Link]
Operators and Statements
• Almost same set of operators as Java
– + (addition and String concatenation), -, *, /
– &&, ||, ++, --, etc
– The == comparison is more akin to Java's "equals"
– The === operator (less used) is like Java's ==
• Statements
– Semicolons are technically optional
• But highly recommended
– Consider
• return x
• return
x
• They are not identical! The second one returns, then evaluates
x. Act as though semicolons are required as in Java.
• Comments
– Same as in Java (/* ... */ and // ...)
18 Java EE training: [Link]

Conditionals and Simple Loops


• if/else
– Almost identical to Java except test can be converted to
true/false instead of strict true/false
• 0 is false, 1 is true
• Many people avoid this and use strict booleans
• Basic for loop
– Identical to Java except for variable declarations
• for(var i=0; i<someVal; i++) { doLoopBody(); }
• while loop
– Same as Java except test can be converted to boolean
• while(someTest) { doLoopBody(); }
• do/while loop
19
– Same as Java except test can beJavaconverted to boolean
EE training: [Link]
Array Basics
• One-step array allocation
– var primes = [2, 3, 5, 7, 11, 13];
– var names = ["Joe", "Jane", "John", "Juan"];
• Two-step array allocation
– var names = new Array(4);
names[0] = "Joe";
...
names[3] = "Juan";
• Indexed at 0 as in Java
– for(var i=0; i<[Link]; i++) {
doSomethingWith(names[i]);
}
20 Java EE training: [Link]

Other Conditionals and Loops


• switch
– Differs from Java in two ways
• The "case" can be an expression
• Values need not be ints (compared with ===)
• for/in loop
– Similar to Java for/each loop, but
• For arrays, values are array indexes, not array values
– Indexes are treated as strings ("0")
– Shows only indexes with values
• For objects, values are the property names
– var names = ["Joe", "Jane", "John", "Juan"];
for(var i in names) {
doSomethingWith(names[i]);
21
} Java EE training: [Link]
More on Arrays
• Arrays can be sparse
– var names = new Array();
names[0] = "Joe";
names[100000] = "Juan";
• Arrays can be resized
– Regardless of how arrays is created, you can do:
• [Link] = someNewLength;
• myArray[anyNumber] = someNewValue;
– This is legal regardless of which way myArray was made
• Arrays have methods
– join, reverse, sort, concat, slice, splice, toString, etc.
• See API reference
• Regular objects can be treated like arrays
– You can use numbers (indexes) as properties
22 Java EE training: [Link]

Arrays Example
function arrayLoops() {
var names =
["Joe", "Jane",
"John", "Juan"];
printArray1(names);
printArray2(names);
[Link] = 10;
printArray1(names);
printArray2(names);
}

function printArray1(array) {
for(var i=0; i<[Link]; i++) {
[Link]("[printArray1] array[%o] is %o", i, array[i]);
}
}
[Link] is a printf-like way to print output in Firebug
function printArray2(array) { Console window. For testing/debugging only.
for(var i in array) {
[Link]("[printArray2] array[%o] is %o", i, array[i]);
} Direct call for interactive testing in Firebug console.
} (Cut/paste all code into console command line.)
23 arrayLoops();
Java EE training: [Link]
The Math Class
• Almost identical to Java
– Like Java, static methods ([Link], [Link], etc.)
– Like Java, logs are base e, trig functions are in radians
• Functions
– [Link], [Link], [Link], [Link], Math.atan2,
[Link], [Link], [Link], [Link], [Link],
[Link], [Link], [Link], [Link],
[Link], [Link], [Link], [Link]
• Constants
– Math.E, Math.LN10, Math.LN2, Math.LOG10E,
[Link], Math.SQRT1_2, Math.SQRT2

24 Java EE training: [Link]

© 2008 Marty Hall

Strings and
Regular Expressions

Customized Java EE Training: [Link]


Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Basics
• You can use double or single quotes
– var names = ["Joe", 'Jane', "John", 'Juan'];
• You can access length property
– E.g., "foobar".length returns 6
• Numbers can be converted to strings
– Automatic conversion during concatenations.
String need not be first as in Java
• var val = 3 + "abc" + 5; // Result is "3abc5"
– Conversion with fixed precision
• var n = 123.4567;
var val = [Link](2); // Result is 123.46 (not 123.45)
• Strings can be compared with ==
– "foo" == 'foo' returns true
• Strings can be converted to numbers
– var i = parseInt("37 blah"); // Result is 37 – ignores blah
– var d = parseFloat("6.02 blah"); // Ignores blah
26 Java EE training: [Link]

Core String Methods


• Simple methods similar to Java
– charAt, indexOf, lastIndexOf, substring, toLowerCase,
toUpperCase
• Methods that use regular expressions
– match, replace, search, split
• HTML methods
– anchor, big, bold, fixed, fontcolor, fontsize, italics, link,
small, strike, sub, sup
• "test".bold().italics().fontcolor("red") returns
'<font color="red"><i><b>test</b></i></font>'
– These are technically nonstandard methods, but supported
in all major browsers
• But I prefer to construct HTML strings explicitly anyhow
27 Java EE training: [Link]
Regular Expressions
• You specify a regexp with /pattern/
– Not with a String as in Java
• Most special characters same as in Java
– ^, $, . – beginning, end of string, any one char
– \ – escape what would otherwise be a special character
– *, +, ? – 0 or more, 1 or more, 0 or 1 occurrences
– {n}, {n,} – exactly n, n or more occurrences
– [] – grouping
– \s, \S – whitespace, non-whitespace
– \w, \W – word char (letter or number), non-word char
• Modifiers
– /pattern/g – do global matching (find all matches, not just first one)
– /pattern/i – do case-insensitive matching
– /pattern/m – do multiline matching
28 Java EE training: [Link]

Regular Expression: Examples

29 Java EE training: [Link]


More Information on Regular
Expressions
• Online API references given earlier
(See RegExp class)
– [Link]
– [Link]
QuickRef/[Link]
• JavaScript Regular Expression Tutorials
– [Link]
JavaScript/17/36435/
– [Link]

30 Java EE training: [Link]

© 2008 Marty Hall

Functions

Customized Java EE Training: [Link]


Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Overview
• Not similar to Java
– JavaScript functions very different from Java methods
• Main differences from Java
– You can have global functions
• Not just methods (functions as part of objects)
– You don't declare return types or argument types
– Caller can supply any number of arguments
• Regardless of how many arguments you defined
– Functions are first-class datatypes
• You can pass functions around, store them in arrays, etc.
– You can create anonymous functions (closures)
• Critical for Ajax
• These are equivalent
– function foo(...) {...}
32
– var foo = function(...) {...}
Java EE training: [Link]

Passing Functions: Example


function third(x) {
return(x / 3);
}

function triple(x) {
return(x * 3);
}

function nineTimes(x) {
return(x * 9);
}
Function as argument.

function operate(f) {
var nums = [1, 2, 3];
for(var i=0; i<[Link]; i++) {
var num = nums[i];
[Link]("Operation on %o is %o.",
num, f(num));
}
}
33 Java EE training: [Link]
Anonymous Functions
• Anonymous functions (or closures) let you
capture local variables inside a function
– You can't do Ajax without this!
• Basic anonymous function
– operate(function(x) { return(x * 20); });
• Outputs 20, 40, 60
• The "operate" function defined on previous page
• Anonymous function with captured data
– function someFunction(args) {
var val = someCalculation(args);
return(function(moreArgs) {
doSomethingWith(val, moreArgs);
});
}
var f1 = someFunction(args1);
var f2 = someFunction(args2);
f1(args3); // Uses one copy of "val"
34
f2(args3); // Uses a different copy of "val"
Java EE training: [Link]

Anonymous Functions: Example


function multiplier(m) {
return(function(x)
{ return(x * m); });
}

function operate2() {
var nums = [1, 2, 3];
var functions =
[multiplier(1/3), multiplier(3), multiplier(9)];
for(var i=0; i<[Link]; i++) {
for(var j=0; j<[Link]; j++) {
var f = functions[i];
var num = nums[j];
[Link]("Operation on %o is %o.",
num, f(num));
}
}
35 } Java EE training: [Link]
Optional Args and Varargs
• You can call any function with any number
of arguments
– If called with fewer args, extra args equal "undefined"
• You can use typeof arg == "undefined" for this
– You can also use boolean comparison if you are sure that no real
value could match (e.g., 0 and undefined both return true for !arg)
• Use comments to indicate optional args
– function foo(arg1, arg2, /* Optional */ arg3) {...}
– If called with extra args, you can use "arguments" array
• Regardless of defined variables, [Link] tells
you how many arguments were supplied, and arguments[i]
returns the designated argument
• Use comments to indicate extra args
– function bar(arg1, arg2 /* varargs */) { ... }
36 Java EE training: [Link]

Optional Arguments
function convertString(numString, /* Optional */ base) {
if (typeof base == "undefined") {
base = 10;
}
var num = parseInt(numString, base);
[Link]("%s base %o equals %o base 10.",
numString, base, num);
}

37 Java EE training: [Link]


Varargs
function longestString(/* varargs */) {
var longest = "";
for(var i=0; i<[Link]; i++) {
var candidateString = arguments[i];
if ([Link] > [Link]) {
longest = candidateString;
}
}
return(longest);
}

longestString("a", "bb", "ccc", "dddd");


// Returns "dddd"

38 Java EE training: [Link]

© 2008 Marty Hall

Objects

Customized Java EE Training: [Link]


Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Basics
• Constructors
– Functions named for class names. Then use "new".
• No separate class definition! No "real" OOP in JavaScript!
– Can define properties with "this"
• You must use "this" for properties used in constructors
function MyClass(n1) { [Link] = n1; }
var m = new MyClass(10);
• Properties (instance variables)
– You don't define them separately
• Whenever you refer to one, JavaScript just creates it
[Link] = 20; // Now [Link] is 10 and [Link] is 20
• Usually better to avoid introducing new properties in
outside code and instead do entire definition in constructor
• Methods
– Properties whose values are functions
40 Java EE training: [Link]

Objects: Example
(Circle Class)
function Circle(radius) {
[Link] = radius;

[Link] =
function() {
return([Link] * this. radius * [Link]);
};
}

var c = new Circle(10);


[Link](); // Returns 314.1592...

41 Java EE training: [Link]


The prototype Property
• In previous example
– Every new Circle got its own copy of radius
• Fine, since radius has per-Circle data
– Every new Circle got its own copy of getArea function
• Wasteful (if many Circles), since function definition never
changes
• Class-level properties
– [Link] = value;
• Methods
– [Link] = function() {...};
• Just a special case of class-level properties
– This is legal anywhere, but it is best to do it in constructor
42 Java EE training: [Link]

Objects: Example
(Updated Circle Class)
function Circle(radius) {
[Link] = radius;

[Link] =
function() {
return([Link] * this. radius * [Link]);
};
}

var c = new Circle(10);


[Link](); // Returns 3.141592...

43 Java EE training: [Link]


Static Methods
• Idea
– Several related functions that do not use object properties
– You want to group them together and call them with
Utils.func1, Utils.func2, etc.
• Grouping is a syntactic convenience. Not real methods.
– Very similar to static methods in Java
• Syntax
– Assign functions to properties of an object, but do not
define a constructor. E.g.,
• var Utils = new Object(); // Or function Utils() {}
[Link] = function(a, b) { … }
[Link] = function(c) {
var x = [Link](val1, val2);
var y = [Link](val3);
44 Java EE training: [Link]

Static Methods: Example (Code)


var MathUtils = new Object();

[Link] = function(n) {
if (n <= 1) {
return(1);
} else {
return(n * [Link](n-1));
}
}

MathUtils.log10 = function(x) {
return([Link](x)/[Link](10));
}

45 Java EE training: [Link]


JSON (JavaScript Object Notation)
• Idea
– A simple textual representation of JavaScript objects
– Main applications
• One-time-use objects (rather than reusable classes)
• Objects received via strings
• Directly in JavaScript
– var someObject =
{ 'property1': value1, // Single or double quotes
'property2': value2,
... };
• In a string (e.g., when coming in on network)
– Surround object representation in parens
46
– Pass to the builtin "eval" function
Java EE training: [Link]

JSON: Example
var person =
{ 'firstName': 'Brendan',
'lastName': 'Eich',
'bestFriend': { 'firstName': 'Chris',
'lastName': 'Wilson' },
'greeting': function() {
return("Hi, I am " + [Link] +
" " + [Link] + ".");
}
};

47 Java EE training: [Link]


Other Object Tricks
• The instanceof operator
– Determines if lhs is a member of class on rhs
• if (blah instanceof Array) {
doSomethingWith([Link]);
}
• The typeof operator
– Returns direct type of operand, as a String
• "number", "string", "boolean", "object", "function", or "undefined".
– Arrays and null both return "object"
• Adding methods to builtin classes
[Link] =
function() { return("My length is " + [Link]); };
"Any Random String".describeLength();
• eval
– Takes a String representing any JavaScript and runs it
• eval("3 * 4 + [Link]"); // Returns 15.141592
48 Java EE training: [Link]

© 2008 Marty Hall

Wrapup

Customized Java EE Training: [Link]


Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Summary
• Use Firebug for testing and debugging
• Bookmark references
– [Link]
• Embedding in browser
– <script src="[Link]" type="test/javascript"></script>
• Basic syntax
– Mostly similar to Java
• Functions
– Very different from Java. Passing functions around and
making anonymous functions very important.
• Objects
– Constructor also defines class. Use "this".
– Not "real" OOP
50 Java EE training: [Link]

© 2008 Marty Hall

Questions?

Customized Java EE Training: [Link]


Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

You might also like