Client side scripting
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Client side scripting

on

  • 1,317 views

 

Statistics

Views

Total Views
1,317
Views on SlideShare
1,317
Embed Views
0

Actions

Likes
0
Downloads
11
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Client side scripting Presentation Transcript

  • 1. Client-side scripting Eleonora Ciceri ciceri@elet.polimi.it
  • 2. Scripts ¤  “A script is a program that automates the execution of tasks which could alternatively be executed one-by-one by a human operator” ¤  Where to use scripts? ¤  Software applications ¤  Web pages ¤  Shells of operating systems ¤  …
  • 3. Scripts: characteristics Programmer ü  Low writing complexity ü  A few lines of code Execution ü  Integration with automatic system configuration (e.g., execute on startup) ü  Absence of graphical interface ü  Call other programs if more complex stuff execution is required
  • 4. Scripting languages ¤  A scripting language is a programming language that supports the writing of scripts ¤  Characteristics ¤  Ease of use: scripting languages are intended to be very fast to pick up and author programs in ¤  OS facilities: built in with easy interfaces ¤  Interpreted from source code: to give the fastest turnaround between the scripting phase and the execution phase
  • 5. Examples of scripting languages ¤  Shell: bash, sh ¤  GUI scripting ¤  Application-specific: e.g., text processing with perl and XSLT ¤  General purpose: Groovy, Perl, Python, Ruby ¤  Web: ¤  Server-side ¤  Client-side: JavaScript, VBScript
  • 6. Interpreter vs. Compiler Interpreter ¤  Source code is executed directly, line by line Compiler ¤  Source code is transformed into binary code (executable file)
  • 7. Comparison: software code The software code is written by the programmer… … then compiled. Errors make the code return to the programmer for further refining A successful compilation process produces machine code The executable file is distributed to the user, who does not access to the code
  • 8. ¤  Scripts have different usages… ¤  Scripts are created and/or modified by the person who executes them ¤  A script is used in order to extend application functionalities, or to execute simple tasks by using pre-existing components Comparison: scripts The script is written by the programmer… … then, neither compiling phase nor linking phase are executed Each line is interpreted, from the top to the bottom An error makes the procedure fail If the execution is ok, the user can see the output
  • 9. Server-side scripting ¤  The server-side scripting comprises all the scripts that are executed on the server ¤  Adopted technologies: Perl, PHP, Coldfusion, XSTL… ¤  The code is not visible to the client ¤  The client receives just the HTML code! The script is written by the programmer… … then it is uploaded on the server REQUEST The HTML code is generated by parsing the script page The user receives just the HTML code (the script code is NOT visible)
  • 10. Client-side scripting ¤  The client-side scripting comprises all the scripts that are executed on the browser ¤  This scripting derives from the event-based programming that is typical of user interfaces ¤  Adopted technologies: Javascript, Vbscript
  • 11. Client-side scripting ¤  The scripts are downloaded by browsers: ¤  Either as a part of an HTML page ¤  Or from external resources linked by a page and retrieved using the HTTP protocol The script is injected in the HTML code REQUEST The user receives the script; the script code IS visible
  • 12. Client-side scripting ¤  The HTML page functionalities are extended, adding a behaviour to it ¤  Examples of added behaviours: ¤  Page updates answering to an user event / a system event The user clicks on a button The browser looks for the part of script related to the “click on button” event If the function is not present, the page does not react If the function is present, the page reacts to the event by applying the suggested behavior
  • 13. Client-side scripting evolution ¤  Past use ¤  Animations of images and menus (e.g., onMouseOver) ¤  Simple widgets (e.g., clock, calendar) ¤  Form validation ¤  Present use ¤  AJAX: Asynchronous JavaScript And XML ¤  Reactive interfaces (similar to desktop applications) ¤  Asynchronous communication between client and server ¤  Separation of computation between client and server ¤  Communication effort reduced
  • 14. Standards
  • 15. Standards: HTML scripting ¤  The HTML scripting is part of the HTML4 recommendation, and it defines: ¤  Where the scripts can be inserted in the HTML markup ¤  Which events control the execution of a script (e.g., events of loading a document or click on a button) ¤  The HTTP protocol functionalities are exploited for retrieving scripts
  • 16. Standards: DOM The DOM (Document Object Model) is an object oriented model for representing HTML and XML documents
  • 17. JavaScript Main concepts
  • 18. JavaScript ¤  JavaScript is the language of the web browser ¤  Good parts ¤  Functions are objects ¤  Dynamic objects (“Want to add another property? Do it!”) ¤  Loose typing ¤  Bad parts ¤  Model based on global variables
  • 19. JavaScript vs. Java ¤  Java and JavaScript share just similarities on the name! ¤  JavaScript is a scripting language ¤  Interpreted ¤  Uses the browser for the input/output procedures ¤  Loose typing ¤  Nothing to be installed (interpreted by the browser, natively) ¤  Java is a programming language ¤  Compiled in bytecode; executed on a virtual machine ¤  Strong typing ¤  Used as a standalone program or as an applet
  • 20. An example: Fibonacci (1) <html>! <head>! !<title>Fibonacci series</title>! !<script language="JavaScript"> !! ...script...! !</script>! </head>! <body>! <button onclick="computeFibonacciSeries()">Compute Fibonacci Series</button>! !<div id="content"></div>! </body>! </html> The results are stored here
  • 21. An example: Fibonacci (2) function computeFibonacciSeries() {! !var contentDiv = document.getElementById("content");! !var header = document.createElement("h3");! !header.appendChild(document.createTextNode("Fibonacci series:"));! !contentDiv.appendChild(header);! ! ! ! !! !var first = 0, second = 1, temp; ! !for(i=1; i<10; i++) { ! temp = first + second; ! contentDiv.appendChild(document.createTextNode(first));! contentDiv.appendChild(document.createElement("br")); ! first = second; ! second = temp; ! !}! };! Retrieve the reference to the div Store the computed number in the content div
  • 22. JavaScript Grammar
  • 23. Grammar: Whitespaces and comments ¤  Whitespace ¤  It can take the form of formatting characters or comments ¤  It is necessary to use whitespace to separate sequences of characters that would be combined into a single token ¤  var that = this;! ¤  Comments ¤  // This is a comment on a line! ¤  /* This is a comment that can be written in multiple lines */!
  • 24. Grammar: Names ¤  A name is a letter optionally followed by one or more letters, digits or underbars ¤  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, while, with!
  • 25. Grammar: Numbers ¤  JavaScript has a single number type (64-bit floating point, the same as Java double) ¤  No separate integer type (1 and 1.0 are the same) ¤  Exponents: 100 = 1e2 ¤  Negative numbers are formed by using the – prefix operator ¤  Special numbers ¤  NaN is the result of an operation that cannot produce a normal result ¤  Infinity represents the infinity value ¤  The Math object contains a set of methods that act on numbers
  • 26. Grammar: Strings ¤  A string can be wrapped in single or double quotes ¤  The char type is not present (use a string containing just one character!) ¤  The “” is the escape character ¤  The length property is used to compute the string length ¤  “seven”.length = 5 ¤  Strings are immutable, i.e., once they are made, they can never be changed ¤  New strings can be created by concatenating other strings with the + operator
  • 27. Grammar: Statements ¤  Each <script> tag delivers a compilation unit that is compiled and immediately executed ¤  Statements are executed from top to bottom ¤  The sequence of execution can be altered by the conditional statements (if and switch), by the looping statements (while, for and do) and by the disruptive statements (break, return and throw) ¤  A block is a set of statements wrapped in curly braces ¤  Blocks do not create a new scope: variables have to be defined at the top of the function, not in blocks
  • 28. Grammar: if statement ¤  if (expression) then {block} else {block}! ¤  False values ¤  False, null, undefined, ‘’, 0, NaN ¤  True values ¤  All the other values
  • 29. Grammar: for statement ¤  for (initialization; condition; increment) {block}! ¤  If the condition is false, the loop breaks ¤  Otherwise, the block is executed, the increment executes, and the loop repeats with the condition ¤  for (variable in object) {block}! ¤  Enumeration of the property names of an object ¤  On each iteration, the current property name is assigned to the variable
  • 30. Grammar: try, catch, throw (1) ¤  The try statement executes a block and catches any exceptions that were thrown by the block ¤  The catch clause defines a new variable that will receive the exception object ¤  The throw statement raises an exception ¤  It throw is in the try block, the control goes to catch! ¤  In throw is not in the try block, the function is abandoned, and the control goes to the catch clause of the try in the calling function
  • 31. Grammar: try, catch, throw (2) Example of throw var add = function(a,b) {! if (typeof a !== ‘number’ || typeof b !== ‘number’) {! throw {! name: ‘TypeError’,! message: ‘add function needs numbers’! };! }! return a + b;! }!
  • 32. Grammar: try, catch, throw (3) Example of try/catch var try_it = function() {! !try {! ! !add(“seven”);! !}! !catch (e) {! ! !document.writeln(e.name + “: “ + e.message);! !}! }!
  • 33. Grammar: return, break! ¤  The return statement causes the early return from a function ¤  A return value can be specified ¤  If the return value is not specified, the return value will be undefined ¤  The break statement causes the exit from a loop statement or a switch statement
  • 34. Grammar: other statements ¤  An expression statement can: ¤  Assign values to one or more variables or members ¤  Invoke a method ¤  Delete a property from an object ¤  The = operator is used for assignment ¤  The === / == operator is the equality operator ¤  ===: equality for both the value and the type ¤  ==: equality for the value ¤  The += operator can add or concatenate
  • 35. Operators Operators Meaning . [] ()! Refinement and invocation delete new typeof + - !! Unary operators * / %! Multiplication, division, modulo + -! Addition/concatenation, subtraction >= <= > <! Inequality === !== == !=! Equality &&! Logical AND ||! Logical OR ?:! Ternary
  • 36. Prefix operators ¤  Typeof ¤  ‘number’, ‘string’, ‘boolean’, ‘undefined’, ‘function’, and ‘object’ Operators Meaning !! Logical not +! Add or concatenate -! Negate
  • 37. Loose typing vs. Strong typing ¤  Most programming languages demand strong typing ¤  Pro: you can detect errors at compile time ¤  Cons: casting between different types ¤  JavaScript is a loosely typed programming language ¤  Pro: no casting between different types ¤  Cons: you cannot understand whether there are errors until you execute the code
  • 38. Javascript: part 2 Eleonora Ciceri Ph.D. student – Politecnico di Milano eleonora.ciceri@polimi.it
  • 39. JavaScript Objects
  • 40. Java: what is an object? ¤  A class defines the data type and allows the creation of objects ¤  The object characteristics reflect the ones required by the class definition maxSpeed doors color myCar = new Car();! myCar adheres to the schema defined when the class was declared There is not the possibility to extend the object by adding and/or removing attributes/methods
  • 41. JavaScript: what is an object? ¤  Well, everything is an object ¤  “Objects are class-free containers used for collecting and organizing data” ¤  Moreover, you can define your own objects Simple data types (Either used as primitive data or objects) ü  Booleans ü  Numbers ü  Strings Complex data types ü  Dates ü  Arrays ü  Functions
  • 42. How to build JavaScript objects ¤  Definition: an object is a special kind of data with: ¤  Properties: the values associated with an object ¤  Methods: the actions that can be performed on an object ¤  How to access to an object? Property objectName.propertyName! Method objectName.methodName() car.color! car.run()!
  • 43. Creating JavaScript objects: Create a direct instance ¤  It is possible to create an object on the fly, by adding properties to it ¤  Translated: 1.  Create an empty object 2.  Add the firstName property with value John! 3.  … person = new Object();! person.firstName = “John”;! person.lastName = “Doe”;! person.age = 50;! person.eyeColor = “blue”;!
  • 44. Creating JavaScript objects: Create a direct instance ¤  Every time a property is added to the definition, the object schema is expanded to contain the new property ¤  This suggests that JavaScript objects are flexible and not tied to a given schema ¤  JavaScript objects are class-free person.firstName! person.firstName! person.lastName! person.firstName! person.lastName! person.age!
  • 45. Creating JavaScript objects: Create an object literal ¤  An object literal is a pair of curly braces surrounding zero or more name/value pairs ¤  This equals to add properties one at a time to the object var empty_object = {};! var employee = {! “first-name”: “Jerome”,! “last-name”: “Howard”! };!
  • 46. Creating JavaScript objects: Use an object constructor ¤  Here comes the this reference: ¤  We are going to handle more than one person at a time ¤  Which person we are dealing must be clear ¤  this indicates the instance of object at hand function person(firstName, lastName, age, eyeColor) {! this.firstName = firstName;! this.lastName = lastName;! this.age = age;! this.eyeColor = color;! }!
  • 47. Creating JavaScript objects: Use an object constructor ¤  Once you have a new constructor, you can create an object instance: ¤  The constructor automatically fills the properties by using the values that are passed as parameters var myFather = new person(“John”,”Doe”,50,”blue”);!
  • 48. Add properties anywhere, anytime ¤  When an object has been created, you can decide to add new properties at each point of your script ¤  The object keeps updating itself every time an expansion is required object = new Object();! object.myProperty = “MyProperty”;! [do some stuff]! [do some other stuff]! object.mySecondProperty = “MySecondProperty”;! [do more and more stuff]! object.myThirdProperty = “MyThirdProperty”;!
  • 49. Adding methods to JavaScript objects ¤  Methods are just functions attached to objects ¤  Their definition is done inside the object constructor function function person(firstName, lastName, age, eyeColor){! this.firstName = firstName;! this.lastName = lastName;! this.age = age;! this.eyeColor = eyeColor;! this.changeName = changeName;! function changeName(name) {! this.lastName = name;! }! } !
  • 50. Adding methods to JavaScript objects ¤  This just expands the object, as in the case of the properties ¤  The only difference is that methods are functions, so they manipulate data rather than adding new fields ¤  The function can be then called on the object: ¤  myMother.changeName(“Doe”);! person.firstName! person.lastName! person.age! person.changeName()!
  • 51. Object prototype ¤  Every object is linked to a prototype object from which it can inherit properties ¤  Object are linked to Object.prototype, an object that comes standard with JavaScript ¤  The prototype link has no effect on updating ¤  Changes to an object do not affect the object’s prototype ¤  The prototype is dynamic ¤  If we add a new property to the prototype, it will be visible in all the objects that are based on the prototype
  • 52. Object prototype Not here? Retry with its prototype Not here? Retry with its prototype … Returns property Returns undefined!
  • 53. Reading properties: Inspection ¤  We have seen that this retrieves a property: person.firstName! ¤  This retrieves exactly the same property: person[firstName]! ¤  And this too: person[“firstName”]!
  • 54. Reading properties: Inspection ¤  So, how to select the appropriate access method? ¤  The quotes are required for names that : ¤  Correspond to reserved words ¤  Contain special characters (e.g., -, _, whitespaces) ¤  The dot notation usage depends on quotes: ¤  Can be used if the property name does not require quotes (but this is not strictly necessary) ¤  Cannot be used if the property name require quotes; in this case, go for []
  • 55. Reading properties: Inspection ¤  We have seen that this returns a property: person[“firstName”]! ¤  We have also seen that strings can be declared either using single quotes or using double quotes ¤  Since the property name is in this case a string, the following returns exactly the same property: person[‘firstName’]!
  • 56. Reading properties: Inspection ¤  The typeof operator reads the property type ¤  The values can correspond either to data or to functions ¤  typeof person.toString returns ‘function’ ¤  The hasOwnProperty method returns true if the object has that particular property, without looking at the prototype chain
  • 57. Reading properties: Enumeration ¤  Now the iteration over the object properties should be clear… ¤  Which is the output? var person = {firstName:”John”, lastName:”Doe”};! text = “”;! for (property in person) {! text = text + person[property] + “ “;! }!
  • 58. Reading properties: Enumeration ¤  Now the iteration over the object properties should be clear… ¤  Which is the output? ¤  N.B. The order in which the properties are printed is not guaranteed var person = {firstName:”John”, lastName:”Doe”};! text = “”;! for (property in person) {! text = text + person[property] + “ “;! }! John Doe
  • 59. Reading non-existing properties ¤  What if we try to access to person.numChildren? ¤  Remember? We didn’t define its value ¤  Yet another difference between Java and JavaScript: ¤  Java: not working ¤  JavaScript: if the value is not defined, and the undefined value is defined: ¤  Since this is not so nice to be handled, we can modify to: ¤  var middle = employee[“middle-name”] || “(none)”;! person.numChildren returns undefined !
  • 60. Reading undefined! ¤  Be really careful: don’t try to access to the internals of undefined! ¤  Attempting to retrieve values from undefined will throw a TypeError exception undefined TypeError
  • 61. Update object properties ¤  If the property already exists, it is replaced: ¤  person[‘firstName’] = ‘John’;! ¤  If the object does not already have that property name, the object is augmented: ¤  person[‘nickname’] = ‘Curly’;!
  • 62. Delete object property ¤  The delete operator removes a property from an object ¤  delete person.nickname! ¤  If a property can’t be deleted, the operation returns false! ¤  N.B. Variables cannot be deleted… ¤  var x = 1;! ¤  delete x; // false! ¤  …and neither can be functions: ¤  function x() {}! ¤  delete x; // false!
  • 63. Object references ¤  Objects are passed around by reference (never copied!) person.name = ‘John’;! var x = person;! x.name = ‘Sam’;! var name = person.name! ‘John’ person
  • 64. Object references ¤  Objects are passed around by reference (never copied!) person.name = ‘John’;! var x = person;! x.name = ‘Sam’;! var name = person.name! ‘John’ person x
  • 65. Object references ¤  Objects are passed around by reference (never copied!) person.name = ‘John’;! var x = person;! x.name = ‘Sam’;! var name = person.name! ‘Sam’ person x
  • 66. Object references ¤  Objects are passed around by reference (never copied!) ! ¤  name is ‘Sam’ because x and person are references to the same object person.name = ‘John’;! var x = person;! x.name = ‘Sam’;! var name = person.name! ‘Sam’ person x name
  • 67. Object references ¤  var a={}, b={}, c={}! ¤  a, b and c refer to different empty objects ¤  var a = b = c = {}! ¤  a, b and c all refer to the same empty object a b c a b c
  • 68. Global objects ¤  All the top-level variables of all compilation units are tossed together in a common namespace called the global object ¤  Needed because: global variables can hold all of the assets of an application ¤  Disadvantage: they increase the possibility that different applications interact badly together, “stealing” other applications’ variables
  • 69. Global objects ¤  Solution: usage of a single global variable! var MYAPP = {};! MYAPP.employee = {! “first-name”: “John”,! “last-name”: “Doe”! };! ¤  Advantages ¤  Reduce the chance of bad interactions with other applications, widgets or libraries ¤  Enhanced readability of the program
  • 70. JavaScript Functions
  • 71. Functions ¤  What is a function? ¤  A block of code that encloses a set of statements ¤  An object ¤  Why do we use functions? ¤  Code reuse ¤  Information hiding ¤  Composition
  • 72. Functions ¤  Since functions are objects, they can be: ¤  Stored in variables, objects and arrays ¤  Passed as arguments to functions ¤  Returned as the result of a function ¤  Functions can have properties and methods
  • 73. Functions that return a function ¤  A function can return another function as return value ¤  There is a really important difference: ¤  Assigning a variable to a function (without the parenthesis) copies the reference to the function ¤  Putting the parenthesis at the end of a function name calls the function and returns the function return value
  • 74. Functions that return a function function a() {! alert('A');! }! //alerts 'A', returns undefined! ! function b() {! alert('B');! return a;! }! //alerts 'B', returns function a! ! function c() {! alert('C');! return a();! }! //alerts 'C', alerts 'A', returns undefined! ! alert("Function 'a' returns " + a());! alert("Function 'b' returns " + b());! alert("Function 'c' returns " + c());!
  • 75. Function closure ¤  Functions can be defined inside other functions ¤  An inner function can access to the parameters and variables of the functions it is nested within ¤  The function object created by a function literal contains a link to that outer context ¤  This is called closure
  • 76. Function closure
  • 77. Function closure This function can see these variables Closure
  • 78. Function closure This function CANNOT see these variables
  • 79. Closure ¤  There are cases when an inner function has a longer lifetime than its outsider function ¤  The closure is adopted to implement private variables, getters and setters var fade = function (node) {! var level = 1;! var step = function () {! var hex = level.toString(16);! node.style.backgroundColor = ‘#FFFF’ + hex + hex;! if (level < 15) {! level += 1;! setTimeout(step,100);! }! };! setTimeout(step,100);! };! This function can see level, and operates on itAll these variables live until the function needs them; when the function terminates, they are deleted
  • 80. Function literals var add = function sum(a,b) {! return a + b;! };! Reserved word Function’s name (optional) •  Used to call the function recursively •  If not defined, the function is said to be anonymous Function’s parameters Parameters are variables in the function, initialized with the provided value Function’s statements The body of the function executed when the function is invoked
  • 81. Scope ¤  A scope defines the visibility and the lifetime of variables and parameters ¤  JavaScript does not have block scope ¤  All the variables defined in a block are not visible from outside the block ¤  JavaScript has function scope ¤  Parameters and variables defined in a function are not visible outside the function ¤  A variable defined in a function is visible in the function ¤  Inner function can access parameter and variables of the function they are defined within
  • 82. Function invocation ¤  Invoking a function suspends the current function ¤  The control is passed to the new function ¤  Parameters are passed too ¤  Passed parameters ¤  The ones specified by the user ¤  this!
  • 83. Function invocation ¤  A function may be called with any number of arguments function go(a,b) {! alert('A=’+ a +’; B=’+ b);! }! go(1)! go(1,2)! go(1,2,3)! a=1,b undefined a=1,b=2 a=1,b=2, third parameter is not listed
  • 84. Function invocation: Method Invocation Pattern ¤  Functions can be stored as properties of an object ¤  The parameter this is bound to that object ¤  It is used to refer to the object when a modification is needed var myObject = {! value: 0,! increment: function (inc) {! this.value += typeof inc === ‘number’ ? inc : 1;! }! };!
  • 85. Function invocation: Function Invocation Pattern ¤  There can be functions which are not properties of an object ¤  These functions are bounded to the global object ¤  A method cannot use an inner function to help if do its work, (the inner function does not share a reference to this) myObject.double = function() {! var that = this;! var helper = function (){! that.value = add(that.value, that.value);! };! helper();! };! To let this function access to this, we have to store a reference to it in the that variable, which is visible in the inner function
  • 86. Function invocation: Constructor Invocation Pattern ¤  The functions invoked with the new prefix are called constructors ¤  When the function is called, a new object is created ¤  The object contains a link to the value of the function’s prototype member var Quo = function(string) {! this.status = string;! };! Quo.prototype.get_status = function() {! return this.status;! };! var myQuo = new Quo(“confused”);! Constructor: this creates an object with a status property Give all instances of Quo a public method called get_status Create a new instance of Quo
  • 87. Function invocation: Apply Invocation Pattern ¤  The apply method allows to ¤  Choose the value of this! ¤  Build an array of arguments to use to invoke a function var array = {3,4};! var sum = add.apply(null, array);! /**********************************/! var Quo = function (string) {! this.status = string;! }! var statusObject = {! status: ‘A-OK’;! };! Status = Quo.prototype.get_status.apply(statusObject);! Create an array of two numbers and add them Create an object with a status member Constructor (see previous slide) The variable Status is equal to ‘A-OK’!
  • 88. Function arguments! ¤  The arguments array is available to functions when they are invoked ¤  The arguments array give access to all the values supplied with the invocation ¤  It includes additional ones, not assigned to parameters ¤  It allows the definition of functions with an unspecified number of parameters ¤  Notice that arguments is not a proper array ¤  It has the length property ¤  It lacks all the other methods
  • 89. Function return! ¤  The last } in a function returns the control to the part of the program that invoked the function ¤  The return statement can be used to cause a function to return early ¤  A function always returns a value ¤  Undefined: if the return value is not specified, then undefined is returned ¤  This: if the function was invoked with the new prefix, then the return value this is returned
  • 90. Callbacks ¤  A callback is useful to deal with discontinuous events ¤  A function can be passed to another function as parameter ¤  This function will be invoked asynchronously ¤  Example: AJAX requests request = prepare_the_request();! ! send_request_asynchronously(! request, ! function (response) {! display(response);! }! };!
  • 91. JavaScript Arrays
  • 92. What is an array? ¤  An array is a linear allocation of memory in which elements are accessed by integers that are used to compute offsets
  • 93. What is an array in JavaScript? ¤  Problem: although they are very efficient and useful, JavaScript does not have them L ¤  Solution: JavaScript provides an object that has some array-like features ¤  Array subscripts are converted into strings and are used as indexes ¤  Elements in an array can contain any mixture of values
  • 94. Example: array misc! var misc = [! ‘string’, 98.6, true, false, null, undefined, [‘nested’, ‘array’], {object: true}, NaN, Infinity! ];! ¤  If misc.length is invoked, the result 10 is retrieved ‘string’ 98.6 true false null undefined ‘nested’ {object:true} NaN Infinity ‘array’ 1 2 3 4 5 6 7 8 9 10
  • 95. Array literal vs. object literal (1) var numbers = [! ‘zero’, ‘one’, ‘two’, ‘three’, ‘four’, ‘five’, ‘six’, ‘seven’, ‘eigth’, ‘nine’! ];! var numbers_object = {! ‘0’: ‘zero’, ‘1’: ‘one’, ‘2’: ‘two’, ‘3’: ‘three’, ‘4’: ‘four’, ‘5’: ‘five’, ‘6’: ‘six’, ‘7’: ‘seven’, ‘8’: ‘eight’, ‘9’: ‘nine’! }! Both numbers and numbers_object are objects with 10 properties, having the same names and values •  numbers inherits from Array.prototype (length property, other array methods) •  numbers_object inherits from Object.prototype (no length property)
  • 96. Array length ¤  The length property is an upper bound ¤  When a subscript greater than the array length is used, this increases the array length ¤  Thus, the length is the largest integer property name in the array plus one, not the number of properties in the array! ¤  Length can be set explicitly ¤  If the length is greater than the number of properties, this does not allocate more space for the array ¤  If the length is smaller than the number of properties, this causes properties to be deleted
  • 97. Modify arrays ¤  The delete operator can be used to remove elements from arrays ¤  This leaves a hole in the array, since the element on the right holds its original name ¤  delete numbers[2];! ¤  The splice method deletes some number of elements and replace them with other elements (specified from the third parameter) ¤  numbers.splice(2,1);! The position from which elements are deleted How many elements are deleted
  • 98. Access to arrays ¤  The for…in operator can be used to iterate over arrays ¤  This works in the same way as accessing to object properties ¤  Problems ¤  No guarantee about the order of the properties ¤  Some browser drags unexpected properties from the prototype chain ¤  Arrays in JavaScript are not initialized (thus missing elements have an undefined value)
  • 99. Matrices ¤  JavaScript does not have multi-dimensional arrays (but one can define arrays of array) …
  • 100. JavaScript Warnings
  • 101. typeof! ¤  The typeof operator returns a string that identifies the type of its operand ¤  Problem: typeof null returns ‘object’ instead of ‘null’ ¤  typeof cannot distinguish between null and objects, but you can because null is false and all objects are true ¤  A better test for null is: myValue === null?
  • 102. Equality ¤  Equality operators are === and !== ¤  If two objects are of the same type and with the same value, then the operator === returns true ¤  The operator == tries to compare objects of different types ‘’ == ‘0’! False 0 == ‘’! True 0 == ‘0’! True false == ‘false’! False false == 0! True false == undefined! False false == null! False null == undefined! True
  • 103. JavaScript: WAT? ¤  WAT? Video (01:20)
  • 104. References
  • 105. References ¤  Wikipedia, “Scripting language” ¤  JavaScript: The Good Parts, Douglas Crockford, O’Reilly ¤  http://javascript.crockford.com/ (videos!) ¤  W3C Javascript Tutorial: http://www.w3schools.com/js/ default.asp ¤  HTML.it Javascript: http://javascript.html.it/
  • 106. References ¤  http://perfectionkills.com/understanding-delete/ ¤  http://www.w3schools.com/js/js_objects.asp