Introduction to JavaScript                          For             Modern Software Development                    Kenneth...
Agenda – before lunch●    History and standard●    Implementations●    Tools●    Syntax●    Procedural programming●    Obj...
Tools●       Syntax highlighting in most editors●       JSLint is a great code checker        ●   http://jslint.com/      ...
Agenda – after lunch●    JavaScript and the browser      ●    Interaction with DOM      ●    JSON      ●    AJAX●    Moder...
Features●    Dynamic      ●    Extending and modifying a running program●    Weakly typed      ●    Implicit type conversi...
History and standard●    Designed by Brendan Eich (Netscape) in 1995      ●    Netscape Communicator 2.0b3 (December 1995)...
Implementations●    Closed source      ●    JScript (Microsoft)      ●    Futhark (Opera)●    Open Source      ●    Spider...
Future implementations●    Just-In-Time (JIT) is becoming popular      ●    V8 is doing it already      ●    TraceMonkey a...
Basic syntax· osd12-js.odp
Syntax – comments and lines●    Just like C      ●    The rest of the line: //      ●    Multi-line: /* */●    // is recom...
Syntax – literals●   Booleans      ●   Examples: true, false      ●   Other false values: null, NaN, , 0, undefined●   Num...
Syntax - names●    Begin with a letter         Reserved words      ●    can be followed by    abstract, boolean, break, by...
Syntax - expression                     literal                     name                                (      expression ...
Syntax – expression ●   typeof(·) returns type of the argument as string      ●   undefined, boolean, number, string, obje...
== vs === ●   == compares values ●   === compares values and types ●   Similar for != and !== ●   Recommendation: use === ...
Arrays ●   Two ways to create an array      ●    Recommended: a = [2.7182, 3.1415]      ●    a = new Array() ●   Zero base...
Procedural programming· osd12-js.odp
Procedural programmingvar                   name                     =   expression                                       ...
Blocks          {            statements          }●    Block is similar to blocks in C      ●    But they do not declare a...
Branches       if         (   expression   )    block    else   block ●   Falsy values for an expression:      ●     false...
Other branches ●   The switch construct is similar to C      ●   Case expressions can be variable      ●   And can be a nu...
Loops ●   Four loops constructions exist      ●    Execute while an expression is true             –   Zero or more times ...
Exceptions          try       block            catch       (   name   )   block      throw             expression         ...
Functions      function   name       (     name       )                                   ,                               ...
Objects· osd12-js.odp
Objects●    Basic object concepts      ●    Javascript has objects      ●    Javascript has no classes●    Mother of all o...
Objects●    Create an object: new Object()●    Indirection: . (dot) or []●    Remove a property using delete●    No protec...
Methods ●   Values can be (anonymous) functions      ●    We call them methods ●   The keyword this refers to the object i...
Simple constructor● Define a functionfunction Graph(title) {      this.title = title;}var g = new Graph(TT);●    Use capit...
Prototype●    Every object has a link to a                                                                           Figur...
Reflection and Enumeration●   typeof returns the type of an object (as string)●   The method hasOwnProperty returns true i...
Example: graphs●   A graph is     ●   A set of nodes and a set of edges (between nodes)●   Directed Acyclic Graph (DAG)   ...
Fluent interfaces ●   Common in OOP and JavaScript      ●    Coined by Martin Fowler      ●    Chaining method invocations...
Functions· osd12-js.odp
Functions●    Functions are objects      ●    Functions can be arguments to           functions                           ...
Anonymous●    Function without a name●    Assign as object to variable●    Useful for callbacksExample: anonymous.js· osd1...
Arguments●    Listed and named parameters are most     common●    Array arguments stores all parameters      ●    Variable...
The meaning of this●    Implicit parameter this refers to the current     context●    Four different invocation patterns  ...
Invocation - Method●    Property in an object      ●    Key concept in OOP●    . (dot) is used to refer to function●    th...
Invocation - Function●    Classical procedural programming      ●    This is set to global scope      ●    Even for inner ...
Invocation - Constructor●    Functions can be used as constructors      ●    The new operator create an object      ●    F...
Invocation - Apply●    The Function object has an apply method      ●    Yes, functions have methods●    apply has two par...
Closure●    Functions have access to the context when     created●    Context will live as long as the function●    Useful...
Functional programming ●   Currying and closures      ●    Rewrite functions: g x  y= f  x , y       ●    Compose func...
JavaScript and the browser· osd12-js.odp
Debugging●    Firebug is an excellent tool      ●    Debugger (break point, single stepping)      ●    HTML and CSS inspec...
Document Object Model●    HTML can be a             <table>     strict file format        <tr><td>X</td><td>Y</td></tr>   ...
DOM and JavaScript●    JavaScript has a runtime library to perform     DOM manipulations●    document is the root●    Give...
JavaScript Object Notation (JSON)●    Serialization format for JavaScript objects      ●   Text representation of object● ...
JSON ●   Browsers have a JSON object      ●    stringify – create JSON representation      ●    parse – create an objectEx...
AJAX ●   Asynchronous Javascript And XML ●   Main concepts      ●    Client-side communication with server      ●    Updat...
Backend●    Server-side programming in any language      ●    Perl, Python, Java, C#●    PHP offers many nice features    ...
Third party libraries●   Open Source libraries try to make cross browser    development easier●   Prototype     ●   Early ...
jQuery●    DOM manipulations●    Forms●    Events●    AJAX●    Fluent interface      ●   $(document.body).css(“background”...
DOM●   $() selects elements based on    ●   Style class    ●   Element ID●   Create and add new elements    ●   .append – ...
Selectors  ●    $(…) is the key function in jQuery  ●    Select DOM elements using CSS selectors  ●    $(…)returns an arra...
Useful methods●    Each – iterator using anonymous function●    Append – add an element●    Remove – delete an element●   ...
Effects●   A queue of effects is maintained    Effects have optional timing parameter      ●   Integer (ms), slow (600 ms)...
Events●    Events trigger callback functions      ●    Anonymous functions are ideal candidates●    Method bind can add a ...
Forms●    Use a selector to find all input elements●    Method serialize is smarter      ●    Find input elements      ●  ...
AJAX ●   $.ajax is your friend      ●    $.ajax(url, { }) ●   Its a remote procedure call/remote method     invokation ●  ...
Drag-n-drop●    Tracking all mouse events      ●    Mouse down to grab element      ●    Follow mouse movement – pixel by ...
JavaScript on the server· osd12-js.odp
Node.js●   Server-side programming●   Based on Googles V8 engine●   Event-driven, non-blocking I/O●   Used by Google, Micr...
Basic use●    Installation      ●    ./configure; make ; make install –           compiles many C++ files!      ●    Or bi...
Modules ●   NODE_PATH sets the path for global modules ●   Either low level C++ modules      ●    This is hard work! ●   O...
Events ●   Objects emit events      ●    When a connection is opened (server)      ●    When a file is opened (file system...
Networking ●   Node.js offers various server classes      ●    net is a general TCP server      ●    http and https are fo...
Get on●    http://ajaxian.com is a great news site for     Javascript developers●    Introduktion til Javascript by K. Gei...
Summary●    Javascript supports three programming     paradigms      ●    Procedural      ●    Object-oriented      ●    F...
Upcoming SlideShare
Loading in …5
×

Introduction to JavaScript for Modern Software Development

3,359 views
3,232 views

Published on

The talk introduces JavaScript for experienced software developer without any knowledge of the language. Moreover, interaction with the browser is presented, and a bit of server-side programming is covered.

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,359
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
19
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Introduction to JavaScript for Modern Software Development

  1. 1. Introduction to JavaScript For Modern Software Development Kenneth Geisshirt http://kenneth.geisshirt.dk/· osd12-js.odp
  2. 2. Agenda – before lunch● History and standard● Implementations● Tools● Syntax● Procedural programming● Object-orientation● Functions as first-class object● Fluent interfaces· osd12-js.odp
  3. 3. Tools● Syntax highlighting in most editors● JSLint is a great code checker ● http://jslint.com/ ● Easy to run using Rhino and integrate with Emacs● Firebug has a nice Javascript debugger ● http://getfirebug.com/● Web developers: use a framework: ● Jquery - http://jquery.com/ ● YUI - http://developer.yahoo.com/yui/ ● Prototype - http://prototypejs.org/ Dojo - http://www.dojotoolkit.org/ ● ● Underscore - http://documentcloud.github.com/underscore/· osd12-js.odp
  4. 4. Agenda – after lunch● JavaScript and the browser ● Interaction with DOM ● JSON ● AJAX● Moderne web programming ● Jquery● Back-end programming ● Node.js· osd12-js.odp
  5. 5. Features● Dynamic ● Extending and modifying a running program● Weakly typed ● Implicit type conversion ● Implicit declared variables● Prototype-based objects ● Objects but no classes● Functions as first-class objects ● A Function is just an object· osd12-js.odp
  6. 6. History and standard● Designed by Brendan Eich (Netscape) in 1995 ● Netscape Communicator 2.0b3 (December 1995) ● Internet Explorer 3.0 (August 1996)● JavaScript is a Oracle trademark● Standardized by ECMA ● Official name ECMAScript ● ECMA-262/ISO-16262 (1997) ● Revision 5.1 is latest revision (June 2011)· osd12-js.odp
  7. 7. Implementations● Closed source ● JScript (Microsoft) ● Futhark (Opera)● Open Source ● SpiderMonkey (Mozilla, written in C) ● Rhino (Mozilla, written in Java) ● QtScript (Nokia Troll Tech) ● JavaScriptCore (Apple) ● V8 (Google)· osd12-js.odp
  8. 8. Future implementations● Just-In-Time (JIT) is becoming popular ● V8 is doing it already ● TraceMonkey and JägerMonkey (Mozilla) ● SquirrelFish (Apple) ● Carakan (Opera) ● Tamparin (Adobe and Mozilla)● Size does matter (smaller is better) ● Transformation and compression of code ● Google Closure· osd12-js.odp
  9. 9. Basic syntax· osd12-js.odp
  10. 10. Syntax – comments and lines● Just like C ● The rest of the line: // ● Multi-line: /* */● // is recommeded by Javascript developers● Statement separator is ; (semicolon)● Statements can span multiple lines● White spaces: space and tab● Case sensitive· osd12-js.odp
  11. 11. Syntax – literals● Booleans ● Examples: true, false ● Other false values: null, NaN, , 0, undefined● Numbers ● Integers – Examples: 42, 101010 ● Real numbers – Examples: 3.1415926535, 6.022e23, 6.626e-34● Strings ● Examples: “Hello”, world, “Dont panic”· osd12-js.odp
  12. 12. Syntax - names● Begin with a letter Reserved words ● can be followed by abstract, boolean, break, byte, letters, digits and case, catch, char, const, continue, underscores (_) debugger, default, delete, do, double, else, enum, export, ● Many extends, false, final, float, for, implementations function, goto, if, implements, import, in, instanceof, int, allow dollar and interface, long, native, new, null, underscore as first package, private, protected, character public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, volatile, void, while, with· osd12-js.odp
  13. 13. Syntax - expression literal name ( expression ) expression operator expression prefix expression function call“hello “+”world”, f(42), 1.0/(x+y), -3.14, 5>7Example: expr.js · osd12-js.odp
  14. 14. Syntax – expression ● typeof(·) returns type of the argument as string ● undefined, boolean, number, string, object, function ● Equality: === and !== ● Inequality: <, >, >=, <= ● Logical: && (and), || (or), ! (not) ● Arithmetic: +, -, *, /, % ● String concatenation: + ● += and -= can be used (but not recommended)Example: opers.js· osd12-js.odp
  15. 15. == vs === ● == compares values ● === compares values and types ● Similar for != and !== ● Recommendation: use === and !==Example: equal.js· osd12-js.odp
  16. 16. Arrays ● Two ways to create an array ● Recommended: a = [2.7182, 3.1415] ● a = new Array() ● Zero based index ● Elements do not have to be of the same type ● Indirection by [] ● Property length is the number of elementsExample: array.js· osd12-js.odp
  17. 17. Procedural programming· osd12-js.odp
  18. 18. Procedural programmingvar name = expression ,● Declare variables ● Only global name space ● No late declarations – Visible in all function ● Interpreter deduces type at runtime· osd12-js.odp
  19. 19. Blocks { statements }● Block is similar to blocks in C ● But they do not declare a scope ● Variables are visible before and after the block ● Advice: declare all variables in the top of functions· osd12-js.odp
  20. 20. Branches if ( expression ) block else block ● Falsy values for an expression: ● false, null, undefined, , 0, NaN ● All other values are trueExample: if.js· osd12-js.odp
  21. 21. Other branches ● The switch construct is similar to C ● Case expressions can be variable ● And can be a number or a string ● Each case must be terminated by breakswitch (c) { case A: break;}Example: switch.js· osd12-js.odp
  22. 22. Loops ● Four loops constructions exist ● Execute while an expression is true – Zero or more times ● do while an expression is true – At least one time ● A for loop while in C ● A for each (for ... in) style of loop – Order is not garantiedExample: loops.js· osd12-js.odp
  23. 23. Exceptions try block catch ( name ) block throw expression ; ● Execution of a block (try) ● All exceptions handled (catch) ● by an exception object (name) ● Any object can be used as exception (throw)Example: exception.js· osd12-js.odp
  24. 24. Functions function name ( name ) , { statements }● Recursion is allowed● Functions can be embedded within function (local function)● Any object can be returned· osd12-js.odp
  25. 25. Objects· osd12-js.odp
  26. 26. Objects● Basic object concepts ● Javascript has objects ● Javascript has no classes● Mother of all objects: Object● Everything is an object ● Booleans, numbers, strings, arrays, functions● An object is a set of properties or key/value pairs● Values can be all kind of objects· osd12-js.odp
  27. 27. Objects● Create an object: new Object()● Indirection: . (dot) or []● Remove a property using delete● No protection of properties· osd12-js.odp
  28. 28. Methods ● Values can be (anonymous) functions ● We call them methods ● The keyword this refers to the object in methods ● Methods can have internal (aux) functionsExample: objects.js· osd12-js.odp
  29. 29. Simple constructor● Define a functionfunction Graph(title) { this.title = title;}var g = new Graph(TT);● Use capital letters for such objects!· osd12-js.odp Example: constructor.js
  30. 30. Prototype● Every object has a link to a Figure parent show() ● The property is named prototype prototype● Differential inheritance position() Box area() ● New object is specified by the difference from its prototype prototype/parent Square ● A long chain of prototypes area() (delegation)· osd12-js.odp Example: differential.js and prototyping.js Square.show()
  31. 31. Reflection and Enumeration● typeof returns the type of an object (as string)● The method hasOwnProperty returns true if object (and not parent) has property● Operator in can give you all propertiesfor (name in obj) { if (typeof(obj[name]) !== function) { console.log(name+: +obj[name]); }}· osd12-js.odp
  32. 32. Example: graphs● A graph is ● A set of nodes and a set of edges (between nodes)● Directed Acyclic Graph (DAG) ● Edges have a direction ● And no loops ● Often used for dependency analysis Emacs Cario libc GTK glib Example: graph.js· osd12-js.odp
  33. 33. Fluent interfaces ● Common in OOP and JavaScript ● Coined by Martin Fowler ● Chaining method invocations  more readable code ● Every method returns reference to objectExamle: fluent.js· osd12-js.odp
  34. 34. Functions· osd12-js.odp
  35. 35. Functions● Functions are objects ● Functions can be arguments to functions Object ● And return value● Scope is a bit tricky ● Function scope and not block scope Function ● Inner functions can access outer functions variables function foo· osd12-js.odp
  36. 36. Anonymous● Function without a name● Assign as object to variable● Useful for callbacksExample: anonymous.js· osd12-js.odp
  37. 37. Arguments● Listed and named parameters are most common● Array arguments stores all parameters ● Variable number of arguments ● Order of parameters and array matches· osd12-js.odp
  38. 38. The meaning of this● Implicit parameter this refers to the current context● Four different invocation patterns ● Method ● Function ● Constructor ● Apply● Current context depends on invocation pattern· osd12-js.odp
  39. 39. Invocation - Method● Property in an object ● Key concept in OOP● . (dot) is used to refer to function● this is set to the object ● Binding of this is done at invocation time ● Access to properties added after adding method· osd12-js.odp
  40. 40. Invocation - Function● Classical procedural programming ● This is set to global scope ● Even for inner functions● Work-around is to save a reference to this ● First statements of outer function:var that;that = this;· osd12-js.odp Example: inner.js
  41. 41. Invocation - Constructor● Functions can be used as constructors ● The new operator create an object ● Functions prototype is used ● this is set to the object ● return will return the object (this)● Close to class-based OOP· osd12-js.odp
  42. 42. Invocation - Apply● The Function object has an apply method ● Yes, functions have methods● apply has two parameters ● Context – or just simply this ● Arguments – stored in arguments· osd12-js.odp Example: apply.js
  43. 43. Closure● Functions have access to the context when created● Context will live as long as the function● Useful patterns ● Return a function ● Callbacks – Anonymous function as parameter to function – Has access to context· osd12-js.odp Example: closure.js
  44. 44. Functional programming ● Currying and closures ● Rewrite functions: g x  y= f  x , y  ● Compose functions: h= f ° g ● Extend Function with a curry methodExamples: highfunc.js· osd12-js.odp
  45. 45. JavaScript and the browser· osd12-js.odp
  46. 46. Debugging● Firebug is an excellent tool ● Debugger (break point, single stepping) ● HTML and CSS inspector ● Network analysis● Cool extensions ● Yslow – give suggesting for better performance ● FireRainbow – syntax highlighting ● FireQuery for jQuery users· osd12-js.odp
  47. 47. Document Object Model● HTML can be a <table> strict file format <tr><td>X</td><td>Y</td></tr> <tr><td>A</td><td>B</td></tr>● Browsers read </table> and parse HTML table● Creates a object tree – aka DOM tr tr● Viewed in Firebug td td td td· osd12-js.odp
  48. 48. DOM and JavaScript● JavaScript has a runtime library to perform DOM manipulations● document is the root● Give relevant HTML elements an ID● onClick property useful● Rich API ● getElementById, appendChild, removeChild, createElementExample: dom.html· osd12-js.odp
  49. 49. JavaScript Object Notation (JSON)● Serialization format for JavaScript objects ● Text representation of object● Useful for client/server communication● Supported by most programming languages { string : value } [ value ] , , Object Array· osd12-js.odp
  50. 50. JSON ● Browsers have a JSON object ● stringify – create JSON representation ● parse – create an objectExample: json.js· osd12-js.odp
  51. 51. AJAX ● Asynchronous Javascript And XML ● Main concepts ● Client-side communication with server ● Update DOM – not reload page ● Smaller, well defined backend functions ● XMLHttpRequest object is the core technology ● Web applications look and feel like desktop applicationsExample: ajax-generic.js, ajax-calc.js, calc.php, calc.html· osd12-js.odp
  52. 52. Backend● Server-side programming in any language ● Perl, Python, Java, C#● PHP offers many nice features ● Parsing of query parameters ● JSON – json_decode creates PHP objects – json_encode serializes PHP_objects – They are slow – use only for small objects! ● Access to libraries (MySQL, etc.)· osd12-js.odp
  53. 53. Third party libraries● Open Source libraries try to make cross browser development easier● Prototype ● Early adaptor – basic functionality ● Scriptacuous (and others) – effects● jQuery ● Heavily used today ● Drupal, Microsoft, and others● YUI – Yahoo! Library● Dojo – avanced but hard to learn· osd12-js.odp
  54. 54. jQuery● DOM manipulations● Forms● Events● AJAX● Fluent interface ● $(document.body).css(“background”,  “black”)● Fancy effects (folding, etc.)● Cool stuff (drag-n-drop, etc.)· osd12-js.odp
  55. 55. DOM● $() selects elements based on ● Style class ● Element ID● Create and add new elements ● .append – add DOM elements after ● .prepend – add DOM element before ● .html – add raw HTML● Delete elements ● .remove – remove elements and its children ● .empty – remove child nodes● Style ● .css – sets using CSS ●· osd12-js.odp
  56. 56. Selectors ● $(…) is the key function in jQuery ● Select DOM elements using CSS selectors ● $(…)returns an array of matching elementsSelector Description#id Elements ID attribute.class CSS class* All elements[attr=”value”] Attribute matchingtag Matching HTML tags Expresion Description parent > child Work on subtree attr$=”value” Match at end Example: selector.html attr^=”value” Match at start · osd12-js.odp attr*=”value” Substring match
  57. 57. Useful methods● Each – iterator using anonymous function● Append – add an element● Remove – delete an element● Empty – delete all element● Html – get or set raw inner HTML of element● Val – get or set the value· osd12-js.odp
  58. 58. Effects● A queue of effects is maintained Effects have optional timing parameter ● Integer (ms), slow (600 ms), fast (200 ms)● Effects can be stopped and dequeuedMethods Effectshow/hide/toogle visibilityfadeIn/fadeOut/fadeToogle Visibility - graduallyslideUp/slideDown/slideToogle Visibility - rollingdelay Pause queue execution· osd12-js.odp
  59. 59. Events● Events trigger callback functions ● Anonymous functions are ideal candidates● Method bind can add a callback function to any element ● click and submit are common events ● $(this) is DOM element as jQuery object● Method unbind removes trigger· osd12-js.odp
  60. 60. Forms● Use a selector to find all input elements● Method serialize is smarter ● Find input elements ● Creates a URL string for the values● Method serializeArray returns an array ● (name, value) pairs● val returns value of first elementExample: form.html· osd12-js.odp
  61. 61. AJAX ● $.ajax is your friend ● $.ajax(url, { }) ● Its a remote procedure call/remote method invokation ● Three important options ● URL – address of backend function ● data – the parameters ● success – call back functionExample: jquery-ajax.html, calc2.php· osd12-js.odp
  62. 62. Drag-n-drop● Tracking all mouse events ● Mouse down to grab element ● Follow mouse movement – pixel by pixel ● Mouse released to drop element⇒ Many lines of code● JQuery simplifies it ● Define areas (source and destination) ● Use draggable and droppable· osd12-js.odp Example: drag-n-drop.html
  63. 63. JavaScript on the server· osd12-js.odp
  64. 64. Node.js● Server-side programming● Based on Googles V8 engine● Event-driven, non-blocking I/O● Used by Google, Microsoft, eBay, LinkedIn, Yahoo!● Modules for ● TCP listeners, buffers, streams, file I/O, etc.● Third party modules ● MySQL, RabbitMQ, ncurses, etc.· osd12-js.odp
  65. 65. Basic use● Installation ● ./configure; make ; make install – compiles many C++ files! ● Or binary packages (Windows, OS X, some Linux distros)● The node or nodejs program is the main program● Load modules using requirevar foo = require(foo)· osd12-js.odp
  66. 66. Modules ● NODE_PATH sets the path for global modules ● Either low level C++ modules ● This is hard work! ● Or written in JavaScript ● Export is used to export functions ● Require is cached ● And cycles can be detectedExample: diff.js, use-diff.js· osd12-js.odp
  67. 67. Events ● Objects emit events ● When a connection is opened (server) ● When a file is opened (file system) ● Add an event listener to handle events ● Use addListener or on ● And removeListener when you dont need it ● Just like in the browserExample: cat.js· osd12-js.odp
  68. 68. Networking ● Node.js offers various server classes ● net is a general TCP server ● http and https are for web servers ● cluster can spawn multiple listeners ● Clients can be written as well ● dns for name look ups ● UDP is also supported through dgramExample: node-http.js· osd12-js.odp
  69. 69. Get on● http://ajaxian.com is a great news site for Javascript developers● Introduktion til Javascript by K. Geisshirt. Libris, 2010.● JavaScript: The Good Parts by D. Crockford. OReilly, 2008● Webmaster in a nutshell by R. Eckstein and S. Spainhour. OReilly, 2002● http://www.wikipedia.org/Javascript· osd12-js.odp
  70. 70. Summary● Javascript supports three programming paradigms ● Procedural ● Object-oriented ● Functional● Under active development ● Revision of the standard ● New engines ● Many frameworks· osd12-js.odp

×