Ajax Basics
Michael Galpin, eBay
Course Agenda
• Jump In > Ajax Basics > Ajax Frameworks • Fundamentals > Intro to JavaScript > Advanced JavaScript > JavaScript Cookbook • Frameworks > Prototype > DojoAjax Basics : Agenda
1.What is Rich User Experience?
2.Rich Internet Application (RIA) Technologies 3.Ajax: Real-life examples & Usage cases
4.What is and Why Ajax? 5.Technologies used in Ajax 6.Anatomy of Ajax operation
7.XMLHttpRequest Methods & Properties 8.DOM APIs & InnerHTML
9.Ajax Security
10.JavaScript debugging tools 11.Current issues and Future
1. Rich User Experience
1. Rich User Experience
for Web Application
Rich User Experience
• Take a look at a typical desktop application (Spreadsheet app, etc.)
• The program responses intuitively and quickly
• The program gives a user meaningful feedback's instantly
> A cell in a spreadsheet changes color when
you hover your mouse over it
> Icons light up as mouse hovers them
• Things happen naturally
> No need to click a button or a link to trigger an
Characteristics of Conventional Web
Applications
•
“Click, wait, and refresh” user interaction
> Page refreshes from the server needed for all
events, data submissions, and navigation
•
Synchronous “request/response”
communication model
> The user has to wait for the response
•
Page-driven: Workflow is based on pages
> Page-navigation logic is determined by the
Issues of Conventional Web Application
• Interruption of user operation
> Users cannot perform any operation while waiting for a response
• Loss of operational context during refresh > Loss of information on the screen
> Loss of scrolled position
• No instant feedback's to user activities > A user has to wait for the next page
• Constrained by HTML > Lack of useful widgets
These are the reasons why Rich Internet Application (RIA) technologies were born.
2. Rich Internet
2. Rich Internet
Application (RIA) Technologies
Rich Internet Application (RIA)
Technologies
•
Java Applet
•
Adobe Flash/Flex
•
Ajax (JavaScript and DHTML)
•
Microsoft Silverlight
Adobe Flash/Flex
•
Designed for playing interactive movies
•
Programmed with ActionScript
•
Pros:
> Good for displaying vector graphics > Excellent tooling
> Browser independent
•
Cons:
> Browser needs a Flash plug-in > ActionScript is proprietary
Ajax
• DHTML = JavaScript + DOM + CSS
• DHTML plus Asynchronous communication capability through XMLHttpRequest
• Pros
> Most viable RIA technology so far > Tremendous industry momentum
> Several toolkits and frameworks are emerging > No need to download code & no plug-in required
• Cons
> Still browser incompatibility
3. Ajax:
3. Ajax:
Real-life Examples &
Real-life Examples &
Usecases
Real-Life Examples of Ajax Apps
•
Outlook Web Access
•
GMail
http://mail.google.com/
•
Flickr
http://flickr.com/
•
http://www.facebook.com/
•
NetFlix
http://www.netflix.com/
Key Aspects of Google Maps
•
A user can drag the entire map by using
the mouse
> Instead of clicking on a button or something
•
The action that triggers the download of
new map data is not a specific click on a
link but a moving the map around
•
Behind the scene - Ajax is used
> The map data is requested and downloaded
asynchronously in the background
•
Other parts of the page remains the same
Use cases for Ajax
•
Real-time server-side input form data
validation
> User IDs, serial numbers, postal codes
> Removes the need to have validation logic at
both client side for user responsiveness and at server side for security and other reasons
•
Auto-completion
> Email address, name, or city name may be
auto-completed as the user types
•
Master detail operation
> Based on a user selection, more detailed
Use cases for AJAX
•
Advanced GUI widgets and controls
> Controls such as tree controls, menus, and
progress bars may be provided that do not require page refreshes
•
Refreshing data
> HTML pages may poll data from a server for
up-to-date data such as scores, stock quotes, weather, or application-specific data
•
Simulating server side notification
> An HTML page may simulate a server-side
notification by polling the server in the background (Comet/Reverse Ajax)
Ajax:
Ajax:
Demo
Demo
Ajax Sample Apps
4. Ajax:
4. Ajax:
What is and Why Ajax?
Why Ajax?
• Intuitive and natural user interaction
> No clicking required
> Mouse movement is a sufficient event trigger
• "Partial screen update" replaces the "click, wait, and refresh" user interaction model
> Only user interface elements that contain new information are updated (fast response)
> The rest of the user interface remains displayed without interruption (no loss of operational context) • Data-driven (as opposed to page-driven)
> UI is handled in the client while the server provides data
Why Ajax?
•
Asynchronous communication replaces
"synchronous request/response model."
> A user can continue to use the application
while the client program requests information from the server in the background
Uninterrupted user operation while data is being fetched Interrupted user operation while the data is being fetched
5. Ajax:
5. Ajax:
Technologies Used
Technologies Used
in Ajax
in Ajax
Technologies Used In Ajax
• Javascript
> Dynamic language
> JavaScript function is called when an event in a page occurs
> Glue for the whole Ajax operation
• DOM
> API for accessing and manipulating structured documents
> Represents the structure of XML and HTML documents
• CSS
> Allows for a clear separation of the presentation style from the content and may be changed programmatically by JavaScript
• XMLHttpRequest
> JavaScript object that performs asynchronous interaction with the server
XMLHttpRequest
•
JavaScript object, invented by Microsoft
•
Adopted by modern browsers
> Mozilla™, Firefox, Safari, and Opera
•
Communicates with a server via standard
HTTP GET/POST
•
XMLHttpRequest object works in the
background for performing asynchronous
communication with the backend server
Server-Side Ajax Request Processing
•
Server programming model remains the
same
> It receives standard HTTP GETs/POSTs > Can use JSP, PHP, ASP.NET ...
•
With minor constraints
> More frequent and finer-grained requests from
client
> Response content type can be
> text/xml
> text/plain
6. Ajax:
6. Ajax:
Anatomy Of
Anatomy Of
Ajax Interaction
Ajax Interaction
using “Data Validation”
using “Data Validation”
Sample Application
Anatomy of an Ajax Interaction
(Data Validation Example)
Steps of AJAX Operation
1.A client event occurs
2.An XMLHttpRequest object is created
3.The XMLHttpRequest object is configured
4.The XMLHttpRequest object makes an async. request
5.The ValidateServlet returns an XML document containing the result
6.The XMLHttpRequest object calls the
callback() function and processes the result
1. A Client event occurs
•
A JavaScript function is called as the result of
an event
•
Example:
validateUserId()
JavaScript function
is mapped as a event handler to a
onkeyup
event on input form field whose id is set to
“
userid
”
<input type="text" size="20" id="userid" name="id" onkeyup="validateUserId();">2. An XMLHttpRequest object is created
var req;
function initRequest() {
if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP");
} }
function validateUserId() { initRequest();
req.onreadystatechange = processRequest;
if (!target) target = document.getElementById("userid"); var url = "validate?id=" + escape(target.value);
req.open("GET", url, true); req.send(null);
3. An XMLHttpRequest object is
configured with a callback function
var req;
function initRequest() {
if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP"); }
}
function validateUserId() { initRequest();
req.onreadystatechange = processRequest; // callback function
if (!target) target = document.getElementById("userid"); var url = "validate?id=" + escape(target.value);
req.open("GET", url, true); req.send(null);
4. XMLHttpRequest object makes an async.
request
function initRequest() {
if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP"); }
}
function validateUserId() { initRequest();
req.onreadystatechange = processRequest;
if (!target) target = document.getElementById("userid");
var url = "validate?id=" + escape(target.value);
req.open("GET", url, true);
req.send(null);
}
5. The ValidateServlet returns an XML
document containing the results (Server)
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String targetId = request.getParameter("id");
if ((targetId != null) && !accounts.containsKey(targetId.trim())) { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("<valid>true</valid>"); } else { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write("<valid>false</valid>"); }
6. XMLHttpRequest object calls callback()
function and processes the result
•
The XMLHttpRequest object was
configured to call the
processRequest()
function when there is a state change to
the
readyState
of the XMLHttpRequest
object
function processRequest() { if (req.readyState == 4) { if (req.status == 200) { var message = ...; ...7. The HTML DOM is updated
•
JavaScript technology gets a reference to
any element in a page using DOM API
•
The recommended way to gain a reference
to an element is to call
> document.getElementById("userIdMessage"),
where "userIdMessage" is the ID attribute of an element appearing in the HTML document
•
JavaScript technology may now be used to
modify the element's attributes; modify the
element's style properties; or add, remove,
or modify child elements
1. <script type="text/javascript">
2. function setMessageUsingDOM(message) {
3. var userMessageElement = document.getElementById("userIdMessage");
4. var messageText;
5. if (message == "false") {
6. userMessageElement.style.color = "red";
7. messageText = "Invalid User Id";
8. } else {
9. userMessageElement.style.color = "green";
10. messageText = "Valid User Id";
11. }
12. var messageBody = document.createTextNode(messageText);
13. // if the messageBody element has been created simple replace it otherwise
14. // append the new element
15. if (userMessageElement.childNodes[0]) { 16. userMessageElement.replaceChild(messageBody, 17. userMessageElement.childNodes[0]); 18. } else { 19. userMessageElement.appendChild(messageBody); 20. } 21.} 22.</script> 23.<body> 24. <div id="userIdMessage"></div> 25.</body>
7. Ajax:
7. Ajax:
XMLHttpRequest
XMLHttpRequest
Methods & Properties
XMLHttpRequest Methods
•
open
(“HTTP method”, “URL”,
syn/asyn
)
> Assigns HTTP method, destination URL, mode
•
send
(content)
> Sends request including string or DOM object data
•
abort
()
> Terminates current request
•
getAllResponseHeaders
()
> Returns headers (labels + values) as a string
•
getResponseHeader
(“header”)
> Returns value of a given header
•
setRequestHeader
(“label”,”value”)
XMLHttpRequest Properties
•
onreadystatechange
> Set with an JavaScript event handler that fires at each state
change
•
readyState
– current status of request
> 0 = uninitialized > 1 = loading
> 2 = loaded
> 3 = interactive (some data has been returned) > 4 = complete
•
status
XMLHttpRequest Properties
•
responseText
> String version of data returned from the server
•
responseXML
> XML document of data returned from the server
•
statusText
8. Ajax: DOM API &
8. Ajax: DOM API &
InnerHTML
Browser and DOM
•
Browsers maintain an object representation
of the documents being displayed
> In the form of Document Object Model (DOM) > It is readily available as document JavaScript
object
•
APIs are available that allow JavaScript
DOM APIs vs. innerHTML
• DOM APIs provide a means for JavaScript code to navigate/modify the content in a page function setMessageUsingDOM(message) { var userMessageElement = document.getElementById("userIdMessage"); var messageText; if (message == "false") { userMessageElement.style.color = "red"; messageText = "Invalid User Id";
} else {
userMessageElement.style.color = "green"; messageText = "Valid User Id";
}
var messageBody = document.createTextNode(messageText); if (userMessageElement.childNodes[0]) { userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]); } else { userMessageElement.appendChild(messageBody); }
DOM APIs vs. innerHTML
• Using innerHTML is easier: Sets or retrieves the HTML between the start and end tags of the
object function setMessageUsingDOM(message) { var userMessageElement = document.getElementById("userIdMessage"); var messageText; if (message == "false") { userMessageElement.style.color = "red"; messageText = "Invalid User Id";
} else {
userMessageElement.style.color = "green"; messageText = "Valid User Id";
}
9. Ajax Security
Ajax Security: Server Side
•
Ajax-based Web applications use the same
server-side security schemes of regular
Web applications
> You specify authentication, authorization, and
data protection requirements in your web.xml file (declarative) or in your program
(programatic)
•
Ajax-based Web applications are subject to
the same security threats as regular Web
applications
> Cross-site scripting
Ajax Security: Client Side
•
JavaScript code is visible to a user/hacker
> Hacker can use the JavaScript code for
inferring server side weaknesses
> Obfustication or compression can be used
•
JavaScript code is downloaded from the
server and executed (“eval”) at the client
> Can compromise the client by mal-intended
code
•
Downloaded JavaScript code is
10. JavaScript Development
10. JavaScript Development
Tools
Development Tools on Mozilla Browser
• Mozilla FireBug debugger (add-on)
> This is the most comprehensive and most useful
JavaScript debugger
• Mozilla JavaScript console
• Mozilla DOM inspector (comes with Firefox package)
• Mozilla Venkman JavaScript debugger (add-on)
• Web Developer Toolbar (add-on)
Mozilla FireBug Debugger
• Spy on XMLHttpRequest traffic
• JavaScript debugger for stepping through code one line at a time
• Inspect HTML source, computed style, events, layout and the DOM
• Status bar icon shows you when there is an error in a web page
• A console that shows errors from JavaScript and CSS • Log messages from JavaScript in your web page to the
console (bye bye "alert debugging")
• An JavaScript command line (no more "javascript:" in the URL bar)
Development Tools on IE
•
Web Developer Toolbar (Firebug for IE)
> Add-on for IE7 (more similar to Web Dev for
Firefox)
> Included with IE8 (like WebDev + Firebug)
•
JavaScript Debugger (free)
•
Visual Studio
11. Ajax:
11. Ajax:
Current Issues & Futures
Current Issues of Ajax
• Complexity is increased
> Server side developers will need to understand that
presentation logic will be required in the HTML client pages as well as in the server-side logic
> Page developers must have JavaScript technology skills
• Ajax-based applications can be difficult to debug, test, and maintain
> JavaScript is hard to test - automatic testing is hard
> Weak modularity in JavaScript - namespace collision possible
> Lack of design patterns or best practice guidelines yet • Multitude of Toolkits
Current Issues of Ajax
•
JavaScript technology dependency &
incompatibility
> Must be enabled for applications to function > Still some browser incompatibilities
•
JavaScript code is visible to a hacker
> Poorly designed JavaScript code can invite
security problem
•
Cross Site Ajax
> Security model only allows XMLHttpRequest to
same domain
Web 2.0 Frameworks
Web 2.0 Frameworks
and Toolkits
and Toolkits
●
Michael Galpin, eBay
Michael Galpin, eBay
Types of Web 2.0 Toolkit and
Framework Solutions of Today
● Clients-side JavaScript Libraries
– Dojo, Prototype, ExtJS, jQuery
● Java World
– RMI-like remoting via proxy (ex: DWR)
– Java to JavaScript/HTML translator (ex: GWT)
● Web Application Frameworks with AJAX
Client Side
Client Side
JavaScript Libraries
JavaScript Libraries
(Examples: Dojo Toolkit,
(Examples: Dojo Toolkit,
Prototype)
Client Side JavaScript Libraries
JavaScript,
DOM Utilities
HTMP, JSP Pages, JavaScript Event Handlers
UI Widgets & Components
Remoting Abstraction Layer
Characteristics of Client Side
JavaScript Libraries
●
Server side technology agnostic
– The server side technology can be Java EE,
.Net, PHP, Ruby on Rails, etc.
●
You can use them in combination in a
single app
– You might want to use widgets and JavaScript
Technical Reasons for using
Client-side JavaScript Libraries
● Handles remote asynch. communication (remoting)
– Hides low-level XMLHttpRequest operation
● Handles browser incompatibilities
– No need to clutter your code with if/else's
● Handles graceful degradation
– Uses IFrame if the browser does not support
XMLHttpRequest
● Provides page navigation hooks over Ajax
Technical Reasons for using
Client-side JavaScript Libraries
● Provides ready-to-use widgets
– Tree, Calendar, Textfield, Button, Split panes, Fisheye, etc.
● Provides easy-to-use DOM utility
– Easier to use than original DOM APIs
● Provides useful JavaScript utilities
– Example: Table management, Timer, etc
● Provides error handling hook
– Easier to add error handler
Technical Reasons for using
Client-side JavaScript Libraries
●
Provides advanced UI features
– Animation– Drag and drop
– Fade out and Fade in
●
Generally encourages OO programming
style
Business Reasons for using
Client-side JavaScript Libraries
●
Proven in the market
– Generally higher quality than your own
●
Established developer/user communities
– Community keeps improving/adding features – Easy to get help from community forums●
Easy to use
– It is just a matter of having them in the root
directory of your Web application or providing URL location
●
Tool support
Client-side JavaScript Libraries
● DOJO Toolkit
– Most comprehensive
– Gaining a leadership in this space – Major industry support (Sun, IBM) – http://dojotoolkit.com/
● Prototype
– Most popular
– Used by other toolkit libaries (Rico, Scriptaculous) – http://prototypejs.org/
● Ext JS
Client-side JavaScript Libraries
● Script.aculo.us
– Built on Prototype
– Nice set of visual effects and controls – http://script.aculo.us/
● Rico
– Built on Prototype
– Rich AJAX components and effects – http://openrico.org/
● jQuery
Demo: Running Various
Demo: Running Various
Client Side JavaScript Toolkit
Client Side JavaScript Toolkit
Demos
Dojo Toolkit
Dojo toolkit
is made of a
set of
layered
libraries
Demo: Building and Running
Demo: Building and Running
Dojo Toolkit Applications
Dojo Demo Scenario
●
Build and run “input validation” Ajax
application using Dojo
– Ajax abstraction – Utility methods
Prototype
●
Ajax abstractions
– Ajax.Updater: uses innerHTML style – Ajax.Request: data-style
●
Ruby like syntax
– Integrated into Rails ●
Most popular kit
– Used by other popular kits
RMI-like Remoting
RMI-like Remoting
via Proxy
via Proxy
(Example: DWR)
(Example: DWR)
RMI-like Remoting via Proxy
HTTP Get/Post
JavaScript RMI like call Java Method
Proxy Skeleton Framework runtime Remote Abstraction Layer XMLHttpRequest iFrame
Why DWR?
● What happens if you have several methods in a class on the server that you want to invoke from the browser?
– Each of these methods need to be addressable
via URI whether you are using
XMLHttpRequest directory or client-side only toolkit such as Dojo or Prototype
– You would have to map parameters and return
values to HTML input form parameters and responses yourself
● DWR provides a client/server framework that addresses these problems
DWR Consists of Two Main
Parts
● A DWR-runtime-provided Java Servlet running on the server
that processes incoming DWR requests and sends responses back to the browser
● org.directwebremoting.servlet.DwrServlet
– This servlet delegates the call to the backend class you
specify in the dwr.xml configuration file
– Alternatively, use annotations
● @RemoteProxy ● @RemoteMethod
● JavaScript running in the browser that sends requests and can
dynamically update the webpage
How Does DWR Work?
● DWR generates a matching client-side Javascript class from a
backend Java class
– Allows you then to write JavaScript code that looks like
conventional RPC/RMI like code, which is much more intuitive than writing raw JavaScript code
● The generated JavaScript class handles remoting details
between the browser and the backend server
– Handles asynchronous communication via
XMLHttpRequest - Invokes the callback function in the
JavaScript
– You provide the callback function as additional parameter – DWR converts all the parameters and return values
Demo: Building and running
Demo: Building and running
DWR Application
DWR Demo Scenario
● Build and run Message Board application ● Create Message service class
– Annotate it to expose via DWR
● Use generated JavaScript
● Write JS to load, persist data using DWR
Java Code To JavaScript/HTML
Java Code To JavaScript/HTML
Translator: GWT
What is GWT?
● Java software development framework that makes writing AJAX applications easy
● Let you develop and debug AJAX applications in the
Java language using the Java development tools of your choice
– NetBeans or Eclipse
● Provides Java-to-JavaScript compiler and a special web browser that helps you debug your GWT
applications
– When you deploy your application to production,
the compiler translates your Java application to browser-compliant JavaScript and HTML
Two Modes of Running GWT
App
● Hosted mode
– Your application is run as Java bytecode within the Java Virtual
Machine (JVM)
– You will typically spend most of your development time in hosted
mode because running in the JVM means you can take advantage of Java's debugging facilities
● Web mode
– Your application is run as pure JavaScript and HTML, compiled
from your original Java source code with the GWT Java-to-JavaScript compiler
– When you deploy your GWT applications to production, you
deploy this JavaScript and HTML to your web servers, so end users will only see the web mode version of your application
Why Use Java Programming
Language for AJAX Development?
● Static type checking in the Java language boosts
productivity while reducing errors.
● Common JavaScript errors (typos, type mismatches) are
easily caught at compile time rather than by users at runtime.
● Code prompting/completion (through IDE) is useful and
widely available
● Automated Java refactoring is pretty snazzy these days. ● Java-based OO designs are easier to communicate and
understand, thus making your AJAX code base more comprehensible with less documentation.
Why GWT?
● No need to learn/use JavaScript language
– Leverage Java programming knowledge you already have
● No need to handle browser incompatibilities and quirks – GWT handles them for you
– Forward/backward buttons – Browser history
● No need to learn/use DOM APIs – Use Java APIs
● No need to build commonly used Widgets – Widgets come with GWT
Why GWT?
● Leverage various tools of Java programming
language for writing/debugging/testing – For example, NetBeans or Eclipse
● JUnit integration
– GWT's direct integration with JUnit lets you unit
test both in a debugger and in a browser and you can even unit test asynchronous RPCs
● Internationalization
– GWT internationalization support provides a
variety of techniques to internationalize strings, typed values, and classes
Demo: Building and running
Demo: Building and running
GWT Applications
GWT Demo Scenario
●
Build and run GWT Stocks
●Debug it in Hosted Mode
●Run in Web Mode
So... What Should I Use?
The JavaScript
Programming Language
Overview
• History • Language • Advanced Features • Platforms • Standards • StyleHistory
The World's Most
Misunderstood
Sources of
Misunderstanding
• The Name • Mispositioning • Design Errors • Bad Implementations • The Browser • Bad Books • Substandard StandardHistory
• 1992
Oak, Gosling at Sun & FirstPerson
• 1995
HotJava
LiveScript, Eich at Netscape
• 1996
JScript at Microsoft
• 1998
Not a Web Toy
• It is a real language
• Small, but sophisticated • It is not a subset of Java
Key Ideas
Key Ideas
• Load and go delivery • Loose typing
• Objects as general containers • Prototypal inheritance
• Lambda
Values
Values
• Numbers • Strings • Booleans • Objects • null • undefinedNumbers
• Only one number type
No integers
• 64-bit floating point
• IEEE-754 (aka “Double”)
• Does not map well to common understanding of arithmetic:
NaN
• Special number: Not a Number
• Result of undefined or erroneous operations
• Toxic: any arithmetic operation with NaN as an input will have NaN as a
result
• NaN is not equal to anything, including NaN
Number function
Number(value)
• Converts the value into a number. • It produces NaN if it has a problem. • Similar to + prefix operator.
parseInt function
parseInt(value, 10)
• Converts the value into a number.
• It stops at the first non-digit character. • The radix (10) should be required.
parseInt("08") === 0
Math
• Math object is modeled on Java's Math class. • It contains
abs absolute value
floor integer
log logarithm
max maximum
pow raise to a power
random random number
round nearest integer
sin sine
Strings
• Sequence of 0 or more 16-bit characters
UCS-2, not quite UTF-16
No awareness of surrogate pairs
• No separate character type
Characters are represented as strings with a length of 1
• Strings are immutable
• Similar strings are equal ( == )
• String literals can use single or double quotes
String length
• string.length
• The length property determines the number of 16-bit characters in a
String function
String(value)
String Methods
• charAt • concat • indexOf • lastIndexOf • match • replace • search • slice • split • substring • toLowerCase • toUpperCaseBooleans
• true • false
Boolean function
Boolean(value)
• returns true if value is truthy • returns false if value is falsy • Similar to !! prefix operator
null
undefined
• A value that isn't even that
• The default value for variables and parameters
• The value of missing members in objects
Falsy values
• false • null • undefined • "" (empty string) • 0 • NaN• All other values (including all objects) are truthy.
Dynamic Objects
• Unification of Object and Hashtable
• new Object() produces an empty container of name/value pairs
• A name can be any string, a value can be any value except undefined
• members can be accessed with dot notation or subscript notation
• No hash nature is visible (no hash codes or rehash methods)
Loosely Typed
• Any of these types can be stored in an variable, or passed as a
parameter to any function
C
• JavaScript is syntactically a C family language
• It differs from C mainly in its type system, which allows functions to be values
Identifiers
• Starts with a letter or _ or $
• Followed by zero or more letters, digits, _ or $ • By convention, all variables, parameters,
members, and function names start with lower case
• Except for constructors which start with upper case
• Initial _ should be reserved for implementations
Reserved Words
abstract
boolean break byte
case catch char class const continue debugger default delete do double
else enum export extends
false final finally float for function goto
if implements import in instanceof int interface
long
native new null
package private protected public return
short static super switch synchronized
this throw throws transient true try typeof var volatile void
Comments
// slashslash line comment /*
slashstar block
comment */
Operators
• Arithmetic + - * / % • Comparison == != < > <= >= • Logical && || ! • Bitwise & | ^ >> >>> << Ternary ?:+
• Addition and concatenation
• If both operands are numbers,
then
add them
else
convert them both to strings concatenate them
+
• Unary operator can convert strings to numbers +"42" = 42 • Also Number("42") = 42 • Also parseInt("42", 10) = 42 +"3" + (+"4") = 7
/
• Division of two integers can produce a non-integer result
== !=
• Equal and not equal
• These operators can do type coercion
• It is better to use === and !==, which do not do type coercion.
&&
• The guard operator, aka logical and
• If first operand is truthy
then result is second operand else result is first operand
• It can be used to avoid null references
if (a) { return a.member; } else { return a; } • can be written as
||
• The default operator, aka logical or
• If first operand is truthy
then result is first operand
else result is second operand
• It can be used to fill in default values. var last = input || nr_items;
• (If input is truthy, then last is input, otherwise set last to nr_items.)
!
• Prefix logical not operator.
• If the operand is truthy, the result is false. Otherwise, the result is true. • !! produces booleans.
Bitwise
& | ^ >> >>> <<
• The bitwise operators convert the operand to a 32-bit signed integer, and turn the result back into 64-bit floating point.
Statements
• expression • if • switch • while • do • for • break • continue • return • try/throwBreak statement
• Statements can have labels.
• Break statements can refer to those labels. loop: for (;;) { ... if (...) { break loop; } ...
For statement
• Iterate through all of the elements of an array:
for (var i = 0; i < array.length; i += 1) {
// within the loop,
// i is the index of the current member
For statement
• Iterate through all of the members of an object:
for (var name in object) {
if (object.hasOwnProperty(name)) {
// within the loop,
// name is the key of current member
// object[name] is the current value
Switch statement
• Multiway branch
• The switch value does not need to a number. It can be a string.
Switch statement
switch (expression) { case ';': case ',': case '.': punctuation(); break; default: noneOfTheAbove(); }Throw statement
throw new Error(reason); throw {
name: exceptionName,
message: reason
Try statement
try { ... } catch (e) { switch (e.name) { case 'Error': ... break; default: throw e; } }Try Statement
• The JavaScript implementation can produce these exception names:
'Error' 'EvalError' 'RangeError' 'SyntaxError' 'TypeError' 'URIError'
With statement
• Intended as a short-hand • Ambiguous • Error-prone • Don't use it with (o) { foo = null; } o.foo = null; foo = null;Function statement
function name(parameters) {
statements;
Var statement
• Defines variables within a function. • Types are not specified.
• Initial values are optional.
var name;
var nrErrors = 0; var a, b, c;
Scope
• In JavaScript, {blocks} do not have scope.
• Only functions have scope.
• Vars defined in a function are not visible outside of the function.
Return statement
return expression;
• or
return;
• If there is no expression, then the return value is undefined.
• Except for constructors, whose default return value is this.
Objects
Objects
• Everything else is objects
• Objects can contain data and methods
• Objects can inherit from other objects
Collections
• An object is an unordered collection of
name/value pairs
• Names are strings
• Values are any type, including other objects
• Good for representing records and trees
Objects:
Objects:
Object Literals
Object Literals
• Object literals are wrapped in { }
• Names can be names or strings • Values can be expressions
• : separates names and values • , separates pairs
• Object literals can be used anywhere a value can appear
Object Literals
var myObject = {name: "Jack B. Nimble", 'goto': 'Jail', grade: 'A', level: 3};
3 "level" "A" "grade" "Jail" "goto" "Jack B. Nimble" "name"
var theName = myObject.name;
Example: maker Function
function maker(name, where, grade, level) { var it = {}; it.name = name; it['goto'] = where; it.grade = grade; it.level = level; return it; }
myObject = maker("Jack B. Nimble", 'Jail', 'A', 3);
Object Literals
var myObject = {name: "Jack B. Nimble",
'goto': 'Jail', grade: 'A', format:
{type: 'rect', width: 1920, height: 1080, interlace: false, framerate: 24}};
Object Literals
var myObject = {
name: "Jack B. Nimble", 'goto': 'Jail', grade: 'A', format: { type: 'rect', width: 1920, height: 1080, interlace: false, framerate: 24 }
Object Literals
myFunction({ type: 'rect', width: 1920, height: 1080 }); throw { name: 'error',Object Literals
function SuperDiv(width, height, left, top, zIndex, position,
color, visibility, html, cssClass)
Objects:
Objects:
Object Augmentation
Object Augmentation
• New members can be added to any object by simple assignment
• There is no need to define a new class
myObject.format.colorModel =
'YCgCb';
Objects:
Objects:
Linkage
Linkage
• Objects can be created with a secret link to another object.
• If an attempt to access a name fails, the secret linked object will be used.
• The secret link is not used when storing. New members are only added to the
primary object.
• The object(o) function makes a new empty object with a link to object o.
Linkage
3 "level" "A" "grade" "Jail" "goto" "Jack B. Nimble" "name"var myNewObject = object(myOldObject);
myNewObject
Linkage
"pignapping" "crime" 4 "level" "Tom Piperson" "name"myNewObject.name = "Tom Piperson"; myNewObject.level += 1; myNewObject.crime = 'pignapping'; "A" "grade" "Jail" "goto" "Jack B. Nimble" "name"
Objects:
Objects:
Inheritance
Inheritance
• Linkage provides simple inheritance. • An object can inherit from an older
Prototypal Inheritance
• Some languages have classes,
methods, constructors, and modules. JavaScript's functions do the work of all of those.
• Instead of Classical Inheritance,
JavaScript has Prototypal Inheritance. • It accomplishes the same things, but
differently.
• It offers greater expressive power.
Prototypal Inheritance
• Instead of organizing objects into rigid
classes, new objects can be made that are similar to existing objects, and then
customized.
• Object customization is a lot less work than making a class, and less overhead, too.
• One of the keys is the object(o) function. • The other key is functions.
Objects:
Objects:
Object Methods
Object Methods
• All objects are linked directly or indirectly to Object.prototype
• All objects inherit some basic methods. • None of them are very useful.
• hasOwnProperty(name)
Is the name a true member of this object?
• No copy method. • No equals method.
Objects:
Objects:
Object Construction
Object Construction
• Make a new empty object
• All three of these expressions have
exactly the same result:
new Object() {}
object(Object.prototype)
Objects:
Objects:
Reference
Reference
• Objects can be passed as
arguments to functions, and can be returned by functions
Objects are passed by reference. Objects are not passed by value.
• The === operator compares object references, not values
true only if both operands are the same object
Delete
• Members can be removed from an object with the delete operator
Arrays
Arrays
• Array inherits from Object.
• Indexes are converted to strings and used as names for retrieving values. • Very efficient for sparse arrays.
• Not very efficient in most other cases. • One advantage: No need to provide a
length
• Arrays, unlike objects, have a special length member.
• It is always 1 larger than the highest integer subscript.
• It allows use of the traditional for statement.
for (i = 0; i < a.length; i += 1) { ...
}
Array Literals
• An array literal uses []
• It can contain any number of
expressions, separated by commas
myList = ['oats', 'peas', 'beans'];
• New items can be appended
myList[myList.length] = 'barley';
• The dot notation should not be used with arrays.
Array Methods
• concat • join • pop • push • slice • sort • spliceDeleting Elements
delete array[number]
• Removes the element, but leaves a hole in the numbering.
array.splice(number, 1) • Removes the element and
renumbers all the following elements.
Deleting Elements
myArray = ['a', 'b', 'c', 'd']; delete myArray[1]; // ['a', undefined, 'c', 'd'] myArray.splice(1, 1); // ['a', 'c', 'd']Arrays v Objects
• Use objects when the names are arbitrary strings.
• Use arrays when the names are sequential integers.
• Don't get confused by the term Associative Array.
Distinguishing Arrays
value.constructor === Array value instanceof Array
Neither of these work when the value comes from a different frame.
Arrays and Inheritance
• Don’t use arrays as prototypes.
The object produced this way does not
have array nature. It will inherit the array's values and methods, but not its length.
• You can augment an individual array. Assign a method to it.
This works because arrays are objects. • You can augment all arrays.
Functions
Functions
• Functions are first-class objects
• Functions can be passed, returned, and stored just like any other value • Functions inherit from Object and
Function operator
• The function operator takes an
optional name, a parameter list, and a block of statements, and returns a function object.
function name(parameters) {
statements
}
• A function can appear anywhere that an expression can appear.
lambda
• What JavaScript calls function, other languages call lambda.
• It is a source of enormous expressive power.
• Unlike most power-constructs, it is secure.
Function statement
• The function statement is just a
short-hand for a var statement with a function value.
function foo() {}
expands to
Inner functions
• Functions do not all have to be defined at the top level (or left edge).
• Functions can be defined inside of other functions.
Scope
• An inner function has access to the variables and parameters of
functions that it is contained within. • This is known as Static Scoping or
Closure
• The scope that an inner function enjoys continues even after the parent functions have returned. • This is called closure.
Closure Example
function fade(id) {
var dom = document.getElementById(id), level = 1; function step () { var h = level.toString(16); dom.style.backgroundColor = '#FFFF' + h + h; if (level < 15) { level += 1; setTimeout(step, 100); } } setTimeout(step, 100);
Function Objects
• Functions are objects, so they can contain name/value pairs.
• This can serve the same purpose as static members in other languages.
Method
• Since functions are values,
functions can be stored in objects. • A function in an object is called a
Invocation
• If a function is called with too many arguments, the extra arguments are ignored.
• If a function is called with too few arguments, the missing values will be undefined.
• There is no implicit type checking on the arguments.
Invocation
• There are four ways to call a function:
Method form
thisObject.methodName(arguments)
thisObject["methodName"](arguments) Function form
functionObject(arguments)
Constructor form
new functionObject(arguments)
Apply form
Method form
thisObject.methodName(arguments)
• When a function is called in the method form, this is set to
thisObject, the object containing the function.
• This allows methods to have a
Function form
functionObject(arguments) • When a function is called in the
function form, this is set to the global object.
That is not very useful.
It makes it harder to write helper functions within a method because the helper function does not get
access to the outer this.
Constructor form
new functionObject(arguments)
• When a function is called with the
new operator, a new object is
created and assigned to this.
• If there is not an explicit return value, then this will be returned.