• Aucun résultat trouvé

[PDF] Manuel de cours sur les bases de php et Ajax [Eng] | Formation informatique

N/A
N/A
Protected

Academic year: 2021

Partager "[PDF] Manuel de cours sur les bases de php et Ajax [Eng] | Formation informatique"

Copied!
593
0
0

Texte intégral

(1)

Ajax Basics

Michael Galpin, eBay

(2)

Course Agenda

• Jump In > Ajax Basics > Ajax Frameworks • Fundamentals > Intro to JavaScript > Advanced JavaScript > JavaScript Cookbook • Frameworks > Prototype > Dojo

(3)

Ajax 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

(4)

1. Rich User Experience

1. Rich User Experience

for Web Application

(5)

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

(6)

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

(7)

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.

(8)

2. Rich Internet

2. Rich Internet

Application (RIA) Technologies

(9)

Rich Internet Application (RIA)

Technologies

Java Applet

Adobe Flash/Flex

Ajax (JavaScript and DHTML)

Microsoft Silverlight

(10)

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

(11)

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

(12)

3. Ajax:

3. Ajax:

Real-life Examples &

Real-life Examples &

Usecases

(13)

Real-Life Examples of Ajax Apps

Outlook Web Access

GMail

http://mail.google.com/

Flickr

http://flickr.com/

Facebook

http://www.facebook.com/

NetFlix

http://www.netflix.com/

(14)

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

(15)

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

(16)

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)

(17)

Ajax:

Ajax:

Demo

Demo

Ajax Sample Apps

(18)

4. Ajax:

4. Ajax:

What is and Why Ajax?

(19)

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

(20)

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

(21)

Uninterrupted user operation while data is being fetched Interrupted user operation while the data is being fetched

(22)
(23)

5. Ajax:

5. Ajax:

Technologies Used

Technologies Used

in Ajax

in Ajax

(24)

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

(25)

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

(26)

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

(27)

6. Ajax:

6. Ajax:

Anatomy Of

Anatomy Of

Ajax Interaction

Ajax Interaction

using “Data Validation”

using “Data Validation”

Sample Application

(28)

Anatomy of an Ajax Interaction

(Data Validation Example)

(29)

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

(30)

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();">

(31)

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);

(32)

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);

(33)

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);

}

(34)

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>"); }

(35)

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 = ...; ...

(36)

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

(37)

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>

(38)

7. Ajax:

7. Ajax:

XMLHttpRequest

XMLHttpRequest

Methods & Properties

(39)

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”)

(40)

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

(41)

XMLHttpRequest Properties

responseText

> String version of data returned from the server

responseXML

> XML document of data returned from the server

statusText

(42)

8. Ajax: DOM API &

8. Ajax: DOM API &

InnerHTML

(43)

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

(44)

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); }

(45)

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";

}

(46)

9. Ajax Security

(47)

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

(48)

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

(49)

10. JavaScript Development

10. JavaScript Development

Tools

(50)

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)

(51)

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)

(52)

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

(53)

11. Ajax:

11. Ajax:

Current Issues & Futures

(54)

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

(55)

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

(56)

Web 2.0 Frameworks

Web 2.0 Frameworks

and Toolkits

and Toolkits

Michael Galpin, eBay

Michael Galpin, eBay

(57)

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

(58)

Client Side

Client Side

JavaScript Libraries

JavaScript Libraries

(Examples: Dojo Toolkit,

(Examples: Dojo Toolkit,

Prototype)

(59)

Client Side JavaScript Libraries

JavaScript,

DOM Utilities

HTMP, JSP Pages, JavaScript Event Handlers

UI Widgets & Components

Remoting Abstraction Layer

(60)

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

(61)

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

(62)

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

(63)

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

(64)

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

(65)

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

(66)

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

(67)

Demo: Running Various

Demo: Running Various

Client Side JavaScript Toolkit

Client Side JavaScript Toolkit

Demos

(68)

Dojo Toolkit

(69)

Dojo toolkit

is made of a

set of

layered

libraries

(70)

Demo: Building and Running

Demo: Building and Running

Dojo Toolkit Applications

(71)

Dojo Demo Scenario

Build and run “input validation” Ajax

application using Dojo

– Ajax abstraction – Utility methods

(72)

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

(73)
(74)

RMI-like Remoting

RMI-like Remoting

via Proxy

via Proxy

(Example: DWR)

(Example: DWR)

(75)

RMI-like Remoting via Proxy

HTTP Get/Post

JavaScript RMI like call Java Method

Proxy Skeleton Framework runtime Remote Abstraction Layer XMLHttpRequest iFrame

(76)

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

(77)
(78)

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

(79)

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

(80)

Demo: Building and running

Demo: Building and running

DWR Application

(81)

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

(82)

Java Code To JavaScript/HTML

Java Code To JavaScript/HTML

Translator: GWT

(83)

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

(84)

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

(85)

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.

(86)

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

(87)

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

(88)

Demo: Building and running

Demo: Building and running

GWT Applications

(89)

GWT Demo Scenario

Build and run GWT Stocks

Debug it in Hosted Mode

Run in Web Mode

(90)

So... What Should I Use?

(91)

The JavaScript

Programming Language

(92)

Overview

• History • Language • Advanced Features • Platforms • Standards • Style

(93)

History

(94)

The World's Most

Misunderstood

(95)

Sources of

Misunderstanding

• The Name • Mispositioning • Design Errors • Bad Implementations • The Browser • Bad Books • Substandard Standard

(96)

History

• 1992

Oak, Gosling at Sun & FirstPerson

• 1995

HotJava

LiveScript, Eich at Netscape

• 1996

JScript at Microsoft

• 1998

(97)

Not a Web Toy

• It is a real language

• Small, but sophisticated • It is not a subset of Java

(98)

Key Ideas

(99)

Key Ideas

• Load and go delivery • Loose typing

• Objects as general containers • Prototypal inheritance

• Lambda

(100)

Values

(101)

Values

• Numbers • Strings • Booleans • Objects • null • undefined

(102)

Numbers

• Only one number type

No integers

• 64-bit floating point

• IEEE-754 (aka “Double”)

• Does not map well to common understanding of arithmetic:

(103)

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

(104)

Number function

Number(value)

• Converts the value into a number. • It produces NaN if it has a problem. • Similar to + prefix operator.

(105)

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

(106)

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

(107)

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

(108)

String length

• string.length

• The length property determines the number of 16-bit characters in a

(109)

String function

String(value)

(110)

String Methods

• charAt • concat • indexOf • lastIndexOf • match • replace • search • slice • split • substring • toLowerCase • toUpperCase

(111)

Booleans

• true • false

(112)

Boolean function

Boolean(value)

• returns true if value is truthy • returns false if value is falsy • Similar to !! prefix operator

(113)

null

(114)

undefined

• A value that isn't even that

• The default value for variables and parameters

• The value of missing members in objects

(115)

Falsy values

• false • null • undefined • "" (empty string) • 0 • NaN

• All other values (including all objects) are truthy.

(116)
(117)

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)

(118)

Loosely Typed

• Any of these types can be stored in an variable, or passed as a

parameter to any function

(119)

C

• JavaScript is syntactically a C family language

• It differs from C mainly in its type system, which allows functions to be values

(120)

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

(121)

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

(122)

Comments

// slashslash line comment /*

slashstar block

comment */

(123)

Operators

• Arithmetic + - * / % • Comparison == != < > <= >= • Logical && || ! • Bitwise & | ^ >> >>> << Ternary ?:

(124)

+

• Addition and concatenation

• If both operands are numbers,

then

add them

else

convert them both to strings concatenate them

(125)

+

• Unary operator can convert strings to numbers +"42" = 42 • Also Number("42") = 42 • Also parseInt("42", 10) = 42 +"3" + (+"4") = 7

(126)

/

• Division of two integers can produce a non-integer result

(127)

== !=

• Equal and not equal

• These operators can do type coercion

• It is better to use === and !==, which do not do type coercion.

(128)

&&

• 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

(129)

||

• 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.)

(130)

!

• Prefix logical not operator.

• If the operand is truthy, the result is false. Otherwise, the result is true. • !! produces booleans.

(131)

Bitwise

& | ^ >> >>> <<

• The bitwise operators convert the operand to a 32-bit signed integer, and turn the result back into 64-bit floating point.

(132)

Statements

• expression • if • switch • while • do • for • break • continue • return • try/throw

(133)

Break statement

• Statements can have labels.

• Break statements can refer to those labels. loop: for (;;) { ... if (...) { break loop; } ...

(134)

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

(135)

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

(136)

Switch statement

• Multiway branch

• The switch value does not need to a number. It can be a string.

(137)

Switch statement

switch (expression) { case ';': case ',': case '.': punctuation(); break; default: noneOfTheAbove(); }

(138)

Throw statement

throw new Error(reason); throw {

name: exceptionName,

message: reason

(139)

Try statement

try { ... } catch (e) { switch (e.name) { case 'Error': ... break; default: throw e; } }

(140)

Try Statement

• The JavaScript implementation can produce these exception names:

'Error' 'EvalError' 'RangeError' 'SyntaxError' 'TypeError' 'URIError'

(141)

With statement

• Intended as a short-hand • Ambiguous • Error-prone • Don't use it with (o) { foo = null; }  o.foo = null;  foo = null;

(142)

Function statement

function name(parameters) {

statements;

(143)

Var statement

• Defines variables within a function. • Types are not specified.

• Initial values are optional.

var name;

var nrErrors = 0; var a, b, c;

(144)

Scope

• In JavaScript, {blocks} do not have scope.

• Only functions have scope.

• Vars defined in a function are not visible outside of the function.

(145)

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.

(146)

Objects

(147)

Objects

• Everything else is objects

• Objects can contain data and methods

• Objects can inherit from other objects

(148)

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

(149)

Objects:

Objects:

Object Literals

(150)

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

(151)

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;

(152)

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);

(153)

Object Literals

var myObject = {name: "Jack B. Nimble",

'goto': 'Jail', grade: 'A', format:

{type: 'rect', width: 1920, height: 1080, interlace: false, framerate: 24}};

(154)

Object Literals

var myObject = {

name: "Jack B. Nimble", 'goto': 'Jail', grade: 'A', format: { type: 'rect', width: 1920, height: 1080, interlace: false, framerate: 24 }

(155)

Object Literals

myFunction({ type: 'rect', width: 1920, height: 1080 }); throw { name: 'error',

(156)

Object Literals

function SuperDiv(width, height, left, top, zIndex, position,

color, visibility, html, cssClass)

(157)

Objects:

Objects:

Object Augmentation

(158)

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';

(159)

Objects:

Objects:

Linkage

(160)

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.

(161)

Linkage

3 "level" "A" "grade" "Jail" "goto" "Jack B. Nimble" "name"

var myNewObject = object(myOldObject);

myNewObject

(162)

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"

(163)

Objects:

Objects:

Inheritance

(164)

Inheritance

• Linkage provides simple inheritance. • An object can inherit from an older

(165)

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.

(166)

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.

(167)

Objects:

Objects:

Object Methods

(168)

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.

(169)

Objects:

Objects:

Object Construction

(170)

Object Construction

• Make a new empty object

• All three of these expressions have

exactly the same result:

new Object() {}

object(Object.prototype)

(171)

Objects:

Objects:

Reference

(172)

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

(173)

Delete

• Members can be removed from an object with the delete operator

(174)

Arrays

(175)

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

(176)

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) { ...

}

(177)

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.

(178)

Array Methods

• concat • join • pop • push • slice • sort • splice

(179)

Deleting 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.

(180)

Deleting Elements

myArray = ['a', 'b', 'c', 'd']; delete myArray[1]; // ['a', undefined, 'c', 'd'] myArray.splice(1, 1); // ['a', 'c', 'd']

(181)

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.

(182)

Distinguishing Arrays

value.constructor === Array value instanceof Array

Neither of these work when the value comes from a different frame.

(183)

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.

(184)

Functions

(185)

Functions

• Functions are first-class objects

• Functions can be passed, returned, and stored just like any other value • Functions inherit from Object and

(186)

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.

(187)

lambda

• What JavaScript calls function, other languages call lambda.

• It is a source of enormous expressive power.

• Unlike most power-constructs, it is secure.

(188)

Function statement

• The function statement is just a

short-hand for a var statement with a function value.

function foo() {}

expands to

(189)

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.

(190)

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

(191)

Closure

• The scope that an inner function enjoys continues even after the parent functions have returned. • This is called closure.

(192)

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);

(193)

Function Objects

• Functions are objects, so they can contain name/value pairs.

• This can serve the same purpose as static members in other languages.

(194)

Method

• Since functions are values,

functions can be stored in objects. • A function in an object is called a

(195)

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.

(196)

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

(197)

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

(198)

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.

(199)

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.

(200)

this

Références

Documents relatifs

Les 79 occurrences du verbe entendre dans les Psaumes se répartissent en fonction de deux niveaux de communication : dans la plus grande partie des textes concernés, c’est

Le système pentecôtiste de gestion de l’argent s’inscrit en effet dans des dispositifs institutionnels de formation, de médiation et d’encadrement dont

Les Français ayant fondé la création d’un État sur une communauté, ils devaient en affirmer l’indépendance religieuse : il s’agissait d’entériner la

Ce que manifeste enfin la confrontation des jugements portés par les voyageurs du XVII e siècle sur les différentes langues orientales, c’est la manière dont

Pourtant, le primat de la joie simple mais tonique qui se dégage de cette fête n’obère en rien ni son côté solennel ni son biblo- centrisme, puisqu’au cœur du programme, comme

C’est d’ailleurs Nicolas Barthélemy lui-même qui nous y pousse, dans un poème adressé au grand humaniste Érasme en 1532 : « Je suis maître d’un collège monastique, prieur

Afin de déterminer le conditionnement optimal de l’essai néoPAMPA, l’évaluation de la stabilité de la cassette de médicaments, de la préparation liposomale et de la

2 Pesquisador(a) do Instituto Capixaba de Pesquisa, Assistência Técnica e Extensão Rural (Incaper); 3 Bolsista FAPES de Iniciação Científica e Tecnológica (ICT);