SlideShare a Scribd company logo
© 2009 Marty Hall




                         JavaScript:
                       A Crash Course
                 Part I: Core Language Syntax
            Originals of Slides and Source Code for Examples:
        http://courses.coreservlets.com/Course Materials/ajax.html
        http://courses.coreservlets.com/Course-Materials/ajax.html
                  Customized Java EE Training: http://courses.coreservlets.com/
  Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
   Developed and taught by well-known author and developer. At public venues or onsite at your location.




                                                                                                                © 2009 Marty Hall




 For live Ajax & GWT training, see training
courses at http://courses.coreservlets.com/.
          t htt //                l t       /
      Taught by the author of Core Servlets and JSP, More
     Servlets and JSP and this tutorial. Available at public
                  JSP,          tutorial
     venues, or customized versions can be held on-site at
                       your organization.
    •C
     Courses d
             developed and t
                 l   d d taught b M t H ll
                             ht by Marty Hall
           – Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF 1.x & 2.0, Ajax, GWT, custom mix of topics
           – Ajax courses can concentrate on EElibrary (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo) or survey several
                  Customized Java one Training: http://courses.coreservlets.com/
    • Courses developed and taught by coreservlets.com experts (edited by Marty)
  Servlets, – Spring, Hibernate/JPA, 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
            JSP, JSF 1.x & JSF EJB3, Ruby/Rails
   Developed and taught by well-known author and developer. At public venues or onsite at your location.
                                           Contact hall@coreservlets.com for details
Topics in This Section
    •   Overview
    •   JavaScript references
    •   Embedding in browser
    •   Basic syntax
    •   Strings and regular expressions
    •   Functions
    •   Objects




5




                                                                                                   © 2009 Marty Hall




                                                  Intro

                        Customized Java EE Training: http://courses.coreservlets.com/
          Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
           Developed and taught by well-known author and developer. At public venues or onsite at your location.
Books
    • JavaScript the Definitive Guide
       – By David Flanagan, O Reilly. The only really complete reference
                   Flanagan O’Reilly
         on the JavaScript language. Thorough and well-written.
           • Makes the global variable blunder when covering Ajax.
    • JavaScript: The Good Parts
       – By Douglas Crockford (of JSON and YUI fame), O’Reilly
       – Outstanding advanced guide to best practices in core JavaScript,
         especially functions, objects, and regular expressions. Very short.
           p      y          , j      ,       g       p             y
           • Does not cover Ajax at all. No DOM scripting. “The K&R of JS”.
    • Pro JavaScript Techniques
       – By John Resig (of jQ y fame), APress
          y           g ( jQuery         ),
       – Excellent guide to best practices; not a thorough reference
           • Does not make the global variable blunder when covering Ajax.
    • DOM Scripting
              p g
       – By Jeremy Keith, FriendsOf Press
       – Focuses on manipulating DOM and CSS
7          • Makes the global variable blunder when briefly covering Ajax.




     Online References
    • JavaScript tutorial (language syntax)
           • http://www w3schools com/js/
             http://www.w3schools.com/js/
           • http://developer.mozilla.org/en/docs/
             Core_JavaScript_1.5_Guide
    • JavaScript API references (builtin objects)
           • http://www.w3schools.com/jsref/
           • http://www.devguru.com/technologies/ecmascript/
             QuickRef/
           • http://www.devguru.com/technologies/JavaScript/
           • http://www.javascriptkit.com/jsref/
           • http://developer.mozilla.org/en/docs/
             Core_JavaScript_1.5_Reference
    • HTML DOM reference (with JavaScript Examples)
           • http://www.w3schools.com/htmldom/dom_reference.asp
    • Official ECMAScript specification
           • http://www.ecma-international.org/publications/standards/
8
             Ecma-262.htm
Firebug
    • Install Firebug in Firefox
      – http://getfirebug.com/
    • Use Firebug console for interactive testing
      – h // fi b
        http://getfirebug.com/cl.html
                             / lh l
    • Can also use Firebug Lite in Internet
      Explorer
      – Not great, but better than nothing
           p g          g
      – http://getfirebug.com/lite.html
         • See especially “bookmarklet” link
    • For more details on Firebug usage
      – See section on Ajax development and debugging tools

9




                                                                                                 © 2009 Marty Hall




        Embedding JavaScript
             in HTML

                      Customized Java EE Training: http://courses.coreservlets.com/
        Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
         Developed and taught by well-known author and developer. At public venues or onsite at your location.
Loading Scripts
     • script with src
                • <script src="my-script.js" type="text/javascript"></script>
          – Purpose
                • To define functions, objects, and variables.
                • Functions will later be triggered by buttons, other user
                  events, inline script tags with body content, etc.
     • script with body content
                • <script type="text/javascript">JavaScript code</script>
          – Purpose
               p
                • To directly invoke code that will run as page loads
                     – E.g., to output HTML content built by JavaScript
                • Don’t use this approach for defining functions or for doing
                  Don t
                  things that could be done in external files.
                     – Slower (no browser caching) and less reusable
11




      Example (phish.js)
     function getMessage() {
       var amount = Math round(Math random() * 100000);
                    Math.round(Math.random()
       var message =
         "You won $" + amount + "!n" +
         "To collect your winnings, send y
                     y                g ,             your credit cardn" +
         "and bank details to oil-minister@phisher.com.";
       return(message);
                           “alert” pops up dialog box
     }

     function showWinnings1() {
       alert(getMessage());
     }                      “document.write” iinserts text into page at current llocation
                            “d      t it ”         t t ti t           t       t      ti


     function showWinnings2() {
       document.write( <h1><blink>
       document write("<h1><blink>" + getMessage() +
                      "</blink></h1>");
     }
12
Example (loading-scripts.html)
     <!DOCTYPE ...><html xmlns="http://www.w3.org/1999/xhtml">
     <head><title>Loading Scripts</title>
     ...
                                                           Loads script from previous page
     <script src="./scripts/phish.js"
             type="text/javascript"></script>
     </head>
     <body>
                                                Calls showWinnings1 when user presses
     ...                                        button. Puts result in dialog box.

         <input type="button" value="How Much Did You Win?"
                onclick='showWinnings1()'/>
     ...
       <script type="text/javascript">showWinnings2()</script>
     ...
     </body></html>
      /      /                          Calls showWinnings2 when page is loaded in
                                                        browser. Puts result at this location in page.


13




      Example (Results)




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




                                                                                                  © 2009 Marty Hall




                              Basic Syntax

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.
Variables
     • Introduce with “var”
       – For global variables (!) and local variables.
       – No “var” for function arguments
     • You do not declare types
       – Some people say JavaScript is “untyped” language, but
         really it is “dynamically typed” language
              y         y        y yp        g g
       – JavaScript is very liberal about converting types
     • There are only two scopes
       – Global scope
            • Be very careful with this when using Ajax.
            • Can cause race conditions
                              conditions.
       – Function (lexical) scope
17     – There is not block scope as in Java




     Operators and Statements
     • Almost same set of operators as Java
       –   + (addition and String concatenation) -, * /
                                  concatenation), *,
       –   &&, ||, ++, --, etc
       –   The == comparison is more akin to Java's "equals"
       –   The === operator (less used) is like Java s ==
                                                Java's
     • Statements
       – Semicolons are technically optional
            • But highly recommended
       – Consider
            • return x
            • return
              x
            • They are not identical! The second one returns, then evaluates
              x. You should act as though semicolons are required as in Java.
     • Comments
       – Same as in Java (/* ... */ and // ...)
18
Conditionals and Simple Loops
     • if/else
       – Almost identical to Java except test can be converted to
         true/false instead of strict true/false
          • “false”: false, null undefined "" (empty string), 0 NaN
             false : false null, undefined,           string) 0,
          • “true”: anything else (including the string “false”)
     • Basic for loop
       – Identical to Java except for variable declarations
          • for(var i=0; i<someVal; i++) { doLoopBody(); }
     • while loop
       – Same as Java except test can be converted to boolean
          • while(someTest) { doLoopBody(); }
     • do/while loop
19
       – Same as Java except test can be converted to boolean




     Array Basics
     • One-step array allocation
       – var primes = [2, 3, 5, 7, 11, 13];
       – var names = ["Joe", "Jane", "John", "Juan"];
          • No trailing comma after last element (see later slide)
     • Two-step array allocation
       – var names = new Array(4);
                             y( );
         names[0] = "Joe";
         ...
         names[3] = "Juan";
                     Juan ;
     • Indexed at 0 as in Java
       – for(var i=0; i<names.length; i++) {
          o (va 0;       a es. e gt ;    )
           doSomethingWith(names[i]);
         }
20
Other Conditionals and Loops
     • switch
       – Differs from Java in two ways
          • The “case” can be an expression
          • Values need not be ints (compared with ===)
                                                      )
     • for/in loop
       – On surface, looks similar to Java for/each loop, but
          • For arrays, values are array indexes, not array values
              – Use this loop for objects (to see property names), not arrays!
                Fails with Prototype or other extended arrays
          • For objects, values are the property names
       – var names = ["Joe", "Jane", "John", "Juan"];
         for(var i in names) {
           doSomethingWith(names[i]);
         }
21




     More on Arrays
     • Arrays can be sparse
       – var names = new A
                         Array();
                              ()
         names[0] = "Joe";
         names[100000] = "Juan";
     • Arrays can be resized
       – Regardless of how arrays is created, you can do:
          • myArray.length = someNewLength;
          • myArray[anyNumber] = someNewValue;
          • myArray.push(someNewValue)
              – These are legal regardless of which way myArray was made
                            g     g                   y y     y
     • Arrays have methods
       – push, pop, join, reverse, sort, concat, slice, splice, etc.
          • See API reference
     • Regular objects can be treated like arrays
22     – You can use numbers (indexes) as properties
Arrays Example
     function arrayLoops() {
       var names =
         ["Joe", "Jane", "John"];
       printArray1(names);
       printArray2(names);
       names.length = 6;
       printArray1(names);
       printArra 1(names)
       printArray2(names);
     }


     function printArray1(array) {
       for(var i=0; i<array.length; i++) {
         console.log("[printArray1] array[%o] is %o", i, array[i]);
       }
     }
                                                                     console.log is a printf-like way to print output in Firebug
     function printArray2(array) {    Console window. For testing/debugging only.
       for(var i in array) {
         console.log("[printArray2] array[%o] is %o", i, array[i]);
       }                             Direct call for interactive testing in Firebug console.
     }                               (Cut/paste all code into console command line.)
23
     arrayLoops();




      Array Performance
                        Time to create and sum array of 16 million random numbers

             9
             8
             7
             6
              5
              4
              3
              2
               1
               0

                     JavaScript:
                              p
                      Firefox 3                     JavaScript:
                                                  Google Chrome                         Java: 1.6_0_10
                      Note: Internet Explorer 7 was more than 10 times slower than Firefox, so times are not shown here.
24                    Source code for benchmarks is in downloadable Eclipse project at coreservlets.com.
The Math Class
     • Almost identical to Java
       – Like Java, static methods (Math.cos, Math.random, etc.)
       – Like Java, logs are base e, trig functions are in radians
     • Functions
       – Math.abs, Math.acos, Math.asin, Math.atan, Math.atan2,
         Math.ceil, Math.cos, Math.exp, Math.floor, Math.log,
                  ,         ,        p,           ,        g,
         Math.max, Math.min, Math.pow, Math.random,
         Math.round, Math.sin, Math.sqrt, Math.tan
     • Constants
       – Math.E, Math.LN10, Math.LN2, Math.LOG10E,
         Math.PI, Math.SQRT1_2, Math.SQRT2
                  Math.SQRT1 2,

25




                                                                                                  © 2009 Marty Hall




                Strings and
            Regular Expressions
              g       p

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




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




     Regular Expression: Examples




30
More Information on Regular
     Expressions
     • Online API references given earlier
       (See R E
       (S RegExp class)
                      l  )
       – http://www.w3schools.com/jsref/jsref_obj_regexp.asp
       – http://www devguru com/technologies/ecmascript/
         http://www.devguru.com/technologies/ecmascript/
         QuickRef/regexp.html
     • JavaScript Regular Expression Tutorials
               p    g       p
       – http://www.evolt.org/article/Regular_Expressions_in_
         JavaScript/17/36435/
       – h //
         http://www.javascriptkit.com/javatutors/re.shtml
                     j     i ki       /j        / h l




31




                                                                                                  © 2009 Marty Hall




                                     Functions
           “It is Lisp in C s clothing.”
            It            C’s clothing.
              - JSON and YUI guru Douglas Crockford, describing
                the JavaScript language in JavaScript: The Good Parts.

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.
Overview
     • Not similar to Java
        –J S i f
         JavaScript functions very diff
                         i         different f
                                             from J
                                                  Java methods
                                                          h d
     • Main differences from Java
        – You can have global functions
           • Not just methods (functions as part of objects)
        – You don’t declare return types or argument types
        – Caller can supply any number of arguments
           • Regardless of how many arguments you defined
        – Functions are first-class datatypes
           • Y can pass f
             You        functions around, store them in arrays, etc.
                            ti         d t      th   i           t
        – You can create anonymous functions (closures)
           • Critical for Ajax
           • These are equivalent
               – function foo(...) {...}
33
               – var foo = function(...) {...}




      Passing Functions: Example
     function third(x) {
       return(x / 3);
     }

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

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

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




      Anonymous Functions: Example
     function multiplier(m) {
       return(function(x)
               { return(x * m); });
     }




     function operate2() {
       var nums = [1, 2, 3];
       var functions =
         [multiplier(1/3), multiplier(3), multiplier(9)];
       for(var i=0; i<functions.length; i++) {
         for(var j=0; j<nums.length; j++) {
           var f = functions[i];
           var num = nums[j];
           console.log("Operation on %o is %o.",
                     g   p
                       num, f(num));
         }
       }
36   }
Optional Args: Summary
     • Fixed number of optional args
       – Functions can always be called with any number of args
       – Compare typeof args to "undefined"
       – See next page and upcoming convertString function
     • Arbitrary args
       – Discover number of args with arguments length
                                      arguments.length
       – Get arguments via arguments[i]
       – See next page and upcoming longestString function
     • Optional args via anonymous object
       – Caller always supplies same number of arguments, but
         one of the arguments is an anonymous (JSON) object
              f th         t i                        bj t
          • This object has optional fields
37     – See later example in “Objects” section




     Optional Args: Details
     • You can call any function with any number
       of arguments
        f
       – If called with fewer args, extra args equal "undefined"
          • You can use typeof arg == "undefined" for this
                                       undefined
              – You can also use boolean comparison if you are sure that no real
                value could match (e.g., 0 and undefined both return true for !arg)
          • Use comments to indicate optional args
              – function foo(arg1, arg2, /* Optional */ arg3) {...}
       – If called with extra args, you can use “arguments” array
          • R
            Regardless of d fi d variables, arguments.length t ll
                  dl     f defined   i bl          t l    th tells
            you how many arguments were supplied, and arguments[i]
            returns the designated argument
          • Use comments to indicate extra args
              – function bar(arg1, arg2 /* varargs */) { ... }
38
Optional Arguments
     function convertString(numString, /* Optional */ base) {
       if (typeof base == "undefined") {
                           undefined )
         base = 10;
       }
       var num = parseInt(numString, base);
       console.log("%s base %o equals %o base 10.",
                   numString, base, num);
     }




39




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

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



40
© 2009 Marty Hall




                                          Objects

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     Basics
     • Constructors
       –F
        Functions named for class names. Then use “
             i        df     l           Th       “new”.
                                                      ”
          • No separate class definition! No “real” OOP in JavaScript!
       – Can define properties with “this”
          • You must use “this” for properties used in constructors
          function MyClass(n1) { this.foo = n1; }
          var m = new MyClass(10);
     • P
       Properties (instance variables)
             ti (i t           i bl )
       – You don’t define them separately
          • Whenever you refer to o e, Ja aSc pt just c eates it
              e e e       ee      one, JavaScript     creates t
          m.bar = 20; // Now m.foo is 10 and m.bar is 20
          • Usually better to avoid introducing new properties in
            outside code and instead do entire definition in constructor
     • Methods
       – Properties whose values are functions
42
Objects: Example
     (Circle Class)
     function Circle(radius) {
       this.radius
       this radius = radius;

         this.getArea =
           function() {
              return(Math.PI * this.radius * this.radius);
           };
     }

     var c = new Circle(10);
     c.getArea(); // Returns 31 1 92
              ()             314.1592...




43




     The prototype Property
     • In previous example
         –E
          Every new Circle got its own copy of radius
                    Ci l       i             f di
            • Fine, since radius has per-Circle data
         – Every new Circle got its own copy of getArea function
            • Wasteful since function definition never changes
     • Class-level properties
         – Classname prototype propertyName = value;
           Classname.prototype.propertyName
     • Methods
         – Classname.prototype.methodName = function() {...};
            • Just a special case of class-level properties
         – This is legal anywhere, but it is best to do it in constructor
     • Pseudo-Inheritance
       Pseudo Inheritance
         – The prototype property can be used for inheritance
44
         – But complex. See later section on Prototype library
Objects: Example
     (Updated Circle Class)
     function Circle(radius) {
       this.radius
       this radius = radius;

         Circle.prototype.getArea =
           function() {
              return(Math.PI * this.radius * this.radius);
           };
     }

     var c = new Circle(10);
     c.getArea(); // Returns 31 1 92
              ()             314.1592...




45




     Rolling Your Own Namespace
     • Idea
         –HHave related f
                   l d functions that do not use object properties
                               i    h d           bj           i
         – You want to group them together and call them with
           Utils.func1, Utils.func2, etc.
            • Grouping is a syntactic convenience. Not real methods.
            • Helps to avoid name conflicts when mixing JS libraries
         – Similar to static methods in Java
     • Syntax
         – Assign functions to properties of an object, but do not
           define a constructor. E.g.,
                    constructor E g
            • var Utils = {}; // Or "new Object()", or make function Utils
              Utils.foo = function(a, b) { … };
              Utils.bar function(c) { … }
              Util b = f         ti ( )    };
              var x = Utils.foo(val1, val2);
46
              var y = Utils.bar(val3);
Static Methods: Example (Code)
     var MathUtils = {};

     MathUtils.fact = function(n) {
        if (n <= 1) {
          return(1);
        } else {
          return(n * MathUtils.fact(n-1));
        }
     };

     MathUtils.log10 = function(x) {
        return(Math.log(x)/Math.log(10));
              (       g( )        g( ))
     };




47




      Namespaces in Real
      Applications
     • Best practices in large projects
        – In many (most?) large projects, all global variables
          (including functions!) are forbidden due to the possibility
          of name collisions from pieces made by different authors.
        – So, these primitive namespaces play the role of Java’s
          packages. Much weaker, but still very valuable.
     • Fancy variation: repeat the name
           • var MyApp = {};
           • MyApp foo = function foo( ) { … };
             MyApp.foo            foo(…)
           • MyApp.bar = function bar(…) { … };
        – The name on the right does not become a global name.
          The l d t
          Th only advantage is for debugging
                             i f d b       i
           • Firebug and other environments will show the name when
48
             you print the function object.
JSON (JavaScript Object Notation)

     • Idea
        – A simple textual representation of JavaScript objects
        – Main applications
           • One time use objects (rather than reusable classes)
             One-time-use
           • Objects received via strings
     • Directly in JavaScript
        – var someObject =
            { property1: value1,
              property2: value2,
              ... };
     • In a string (e.g., when coming in on network)
        – Surround object representation in parens
        – Pass to the builtin “eval” function
49




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




50
Using JSON for Optional
      Arguments
     • Idea
        – Caller always supplies same number of arguments, but
          one of the arguments is an anonymous (JSON) object
             • This object has optional fields
        – This approach is widely used in Prototype, Scriptaculous,
          and other JavaScript libraries
     • Example (a/b: required, c/d/e/f: optional)
        –   someFunction(1.2, 3.4, {c: 4.5, f: 6.7});
        –   someFunction(1.2, 3 4
            someFunction(1 2 3.4, {c: 4.5, d: 6.7, e: 7.8});
                                       45      6 7 7 8});
        –   someFunction(1.2, 3.4, {c: 9.9, d: 4.5, e: 6.7, f: 7.8});
        –   someFunction(1.2, 3.4);
                        ( , );

51




      Using JSON for Optional
      Arguments: Example Code
     function sumNumbers(x, y, extraParams) {
       var result = x + y;
       if (isDefined(extraParams)) {
         if (isTrue(extraParams.logInput)) {
           console.log("Input: x=%s, y=%s", x, y);
         }
         if (isDefined(extraParams.extraOperation)) {
           result = extraParams.extraOperation(result);
         }
       }
       return(result)
     }

     function isDefined(value) {
       return(typeof value != "undefined");
     }

     function isTrue(value) {
       return(isDefined(value) && (value == true))
52   }
Using JSON for Optional
     Arguments: Example Results




53




     Internet Explorer and Extra
     Commas
     • Firefox tolerates trailing commas in both
       arrays and JSON
                 d
          • var nums = [1, 2, 3, ];
          • var obj = { firstName: "Joe", lastName: "Hacker", };
                                    Joe ,            Hacker ,
     • IE will crash in both cases.
       – And, since it is not technically legal anyway, you should
         write it without commas after the final element:
          • var nums = [1, 2, 3];
          • var obj = { firstName: "Joe", lastName: "Hacker"};
                                    Joe ,            Hacker };
       – This issue comes up moderately often, especially when
         building JavaScript data on the server, as we will do in
         upcoming lectures.
                i l t

54
Other Object Tricks
     • The instanceof operator
       –D
        Determines if lhs is a member of class on rhs
              i       lh i        b    f l         h
          • if (blah instanceof Array) {
              doSomethingWith(blah.length);
            }
     • The typeof operator
       – Returns direct type of operand, as a String
          • "number", "string", "boolean", "object", "function", or "undefined".
                 – Arrays and null both return "object"
     • Adding methods to builtin classes
            g
       String.prototype.describeLength =
           function() { return("My length is " + this.length); };
       "Any Random String".describeLength();
     • eval
       – Takes a String representing any JavaScript and runs it
          • eval("3 * 4 + Math.PI");                      // Returns 15.141592
55




                                                                                                  © 2009 Marty Hall




                                         Wrap-up

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.
Summary
     • Use Firebug for testing and debugging
     • B k
       Bookmark references
                k f
       – http://www.w3schools.com/js/
     • Embedding in browser
       – <script src="blah.js" type="test/javascript"></script>
     • Basic syntax
       – Mostly similar to Java
     • Functions
       – Totally different from Java. Passing functions around and
                                Java
         making anonymous functions very important.
     • Objects
       – Constructor also defines class. Use “this”.
       – Totally different from Java. Not like classical OOP at all.
57




                                                                                                  © 2009 Marty Hall




                                  Questions?

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.

More Related Content

What's hot

Django in the Real World
Django in the Real WorldDjango in the Real World
Django in the Real World
Jacob Kaplan-Moss
 
HTML, CSS & Javascript Architecture (extended version) - Jan Kraus
HTML, CSS & Javascript Architecture (extended version) - Jan KrausHTML, CSS & Javascript Architecture (extended version) - Jan Kraus
HTML, CSS & Javascript Architecture (extended version) - Jan Kraus
Women in Technology Poland
 
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Matt Raible
 
WordPress and Ajax
WordPress and AjaxWordPress and Ajax
WordPress and Ajax
Ronald Huereca
 
遇見 Ruby on Rails
遇見 Ruby on Rails遇見 Ruby on Rails
遇見 Ruby on Rails
Wen-Tien Chang
 
Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014
Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014
Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014
David Delabassee
 
Server Side Javascript
Server Side JavascriptServer Side Javascript
Server Side Javascript
rajivmordani
 
Howtobuildyourownframework
HowtobuildyourownframeworkHowtobuildyourownframework
Howtobuildyourownframework
hazzaz
 
Django Performance Recipes
Django Performance RecipesDjango Performance Recipes
Django Performance Recipes
Jon Atkinson
 
2013 04-02-server-side-backbone
2013 04-02-server-side-backbone2013 04-02-server-side-backbone
2013 04-02-server-side-backbone
SC5.io
 
Java script by Act Academy
Java script by Act AcademyJava script by Act Academy
Java script by Act Academy
actanimation
 
Tools and Tips for Moodle Developers - #mootus16
 Tools and Tips for Moodle Developers - #mootus16 Tools and Tips for Moodle Developers - #mootus16
Tools and Tips for Moodle Developers - #mootus16
Dan Poltawski
 
HTML 5 - Overview
HTML 5 - OverviewHTML 5 - Overview
HTML 5 - Overview
Marcelio Leal
 
Progressive Downloads and Rendering - take #2
Progressive Downloads and Rendering - take #2Progressive Downloads and Rendering - take #2
Progressive Downloads and Rendering - take #2
Stoyan Stefanov
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
PHP MVC Tutorial
PHP MVC TutorialPHP MVC Tutorial
PHP MVC Tutorial
Yang Bruce
 
End-to-end testing with geb
End-to-end testing with gebEnd-to-end testing with geb
End-to-end testing with geb
Jesús L. Domínguez Muriel
 
Developing web applications in 2010
Developing web applications in 2010Developing web applications in 2010
Developing web applications in 2010
Ignacio Coloma
 

What's hot (19)

Django in the Real World
Django in the Real WorldDjango in the Real World
Django in the Real World
 
HTML, CSS & Javascript Architecture (extended version) - Jan Kraus
HTML, CSS & Javascript Architecture (extended version) - Jan KrausHTML, CSS & Javascript Architecture (extended version) - Jan Kraus
HTML, CSS & Javascript Architecture (extended version) - Jan Kraus
 
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
 
WordPress and Ajax
WordPress and AjaxWordPress and Ajax
WordPress and Ajax
 
遇見 Ruby on Rails
遇見 Ruby on Rails遇見 Ruby on Rails
遇見 Ruby on Rails
 
Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014
Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014
Server Side JavaScript on the JVM - Project Avatar - QCon London March 2014
 
Server Side Javascript
Server Side JavascriptServer Side Javascript
Server Side Javascript
 
Howtobuildyourownframework
HowtobuildyourownframeworkHowtobuildyourownframework
Howtobuildyourownframework
 
Django Performance Recipes
Django Performance RecipesDjango Performance Recipes
Django Performance Recipes
 
2013 04-02-server-side-backbone
2013 04-02-server-side-backbone2013 04-02-server-side-backbone
2013 04-02-server-side-backbone
 
Java script by Act Academy
Java script by Act AcademyJava script by Act Academy
Java script by Act Academy
 
Tools and Tips for Moodle Developers - #mootus16
 Tools and Tips for Moodle Developers - #mootus16 Tools and Tips for Moodle Developers - #mootus16
Tools and Tips for Moodle Developers - #mootus16
 
HTML 5 - Overview
HTML 5 - OverviewHTML 5 - Overview
HTML 5 - Overview
 
Progressive Downloads and Rendering - take #2
Progressive Downloads and Rendering - take #2Progressive Downloads and Rendering - take #2
Progressive Downloads and Rendering - take #2
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
PHP MVC Tutorial
PHP MVC TutorialPHP MVC Tutorial
PHP MVC Tutorial
 
End-to-end testing with geb
End-to-end testing with gebEnd-to-end testing with geb
End-to-end testing with geb
 
Developing web applications in 2010
Developing web applications in 2010Developing web applications in 2010
Developing web applications in 2010
 

Viewers also liked

mapserver_install_linux
mapserver_install_linuxmapserver_install_linux
mapserver_install_linux
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
controlling_animations
controlling_animationscontrolling_animations
controlling_animations
tutorialsruby
 
xampp_server
xampp_serverxampp_server
xampp_server
tutorialsruby
 
LCI2009-Tutorial
LCI2009-TutorialLCI2009-Tutorial
LCI2009-Tutorial
tutorialsruby
 
Agenda
AgendaAgenda

Viewers also liked (7)

mapserver_install_linux
mapserver_install_linuxmapserver_install_linux
mapserver_install_linux
 
Tesi_Adamou
Tesi_AdamouTesi_Adamou
Tesi_Adamou
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
controlling_animations
controlling_animationscontrolling_animations
controlling_animations
 
xampp_server
xampp_serverxampp_server
xampp_server
 
LCI2009-Tutorial
LCI2009-TutorialLCI2009-Tutorial
LCI2009-Tutorial
 
Agenda
AgendaAgenda
Agenda
 

Similar to JavaScript-Core

Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
AkramWaseem
 
Java script core
Java script coreJava script core
Java script core
Vaishnu Vaishu
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
tutorialsruby
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
tutorialsruby
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
snopteck
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
guestcf600a
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
guestcf600a
 
jQuery-3-UI
jQuery-3-UIjQuery-3-UI
jQuery-3-UI
guestcf600a
 
JQuery-Tutorial
 JQuery-Tutorial JQuery-Tutorial
JQuery-Tutorial
tutorialsruby
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
tutorialsruby
 
jQuery-3-UI
jQuery-3-UIjQuery-3-UI
jQuery-3-UI
guestcf600a
 
Ajax basics
Ajax basicsAjax basics
Ajax basics
amanrahulraj
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setup
snopteck
 
DSLs in JavaScript
DSLs in JavaScriptDSLs in JavaScript
DSLs in JavaScript
elliando dias
 
GWT-Basics
GWT-BasicsGWT-Basics
GWT-Basics
tutorialsruby
 
GWT-Basics
GWT-BasicsGWT-Basics
GWT-Basics
tutorialsruby
 
10 jsp-scripting-elements
10 jsp-scripting-elements10 jsp-scripting-elements
10 jsp-scripting-elements
Phạm Thu Thủy
 
15 expression-language
15 expression-language15 expression-language
15 expression-language
snopteck
 

Similar to JavaScript-Core (20)

Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
 
Java script core
Java script coreJava script core
Java script core
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
 
jQuery-3-UI
jQuery-3-UIjQuery-3-UI
jQuery-3-UI
 
JQuery-Tutorial
 JQuery-Tutorial JQuery-Tutorial
JQuery-Tutorial
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
 
jQuery-3-UI
jQuery-3-UIjQuery-3-UI
jQuery-3-UI
 
Ajax basics
Ajax basicsAjax basics
Ajax basics
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setup
 
DSLs in JavaScript
DSLs in JavaScriptDSLs in JavaScript
DSLs in JavaScript
 
GWT-Basics
GWT-BasicsGWT-Basics
GWT-Basics
 
GWT-Basics
GWT-BasicsGWT-Basics
GWT-Basics
 
10 jsp-scripting-elements
10 jsp-scripting-elements10 jsp-scripting-elements
10 jsp-scripting-elements
 
15 expression-language
15 expression-language15 expression-language
15 expression-language
 

More from tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
tutorialsruby
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
tutorialsruby
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
tutorialsruby
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
tutorialsruby
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
tutorialsruby
 
CSS
CSSCSS
CSS
CSSCSS
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
tutorialsruby
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
tutorialsruby
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
tutorialsruby
 

More from tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Recently uploaded

June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 

Recently uploaded (20)

June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 

JavaScript-Core

  • 1. © 2009 Marty Hall JavaScript: A Crash Course Part I: Core Language Syntax Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course Materials/ajax.html http://courses.coreservlets.com/Course-Materials/ajax.html Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. © 2009 Marty Hall For live Ajax & GWT training, see training courses at http://courses.coreservlets.com/. t htt // l t / Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial. Available at public JSP, tutorial venues, or customized versions can be held on-site at your organization. •C Courses d developed and t l d d taught b M t H ll ht by Marty Hall – Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF 1.x & 2.0, Ajax, GWT, custom mix of topics – Ajax courses can concentrate on EElibrary (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo) or survey several Customized Java one Training: http://courses.coreservlets.com/ • Courses developed and taught by coreservlets.com experts (edited by Marty) Servlets, – Spring, Hibernate/JPA, 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. JSP, JSF 1.x & JSF EJB3, Ruby/Rails Developed and taught by well-known author and developer. At public venues or onsite at your location. Contact hall@coreservlets.com for details
  • 2. Topics in This Section • Overview • JavaScript references • Embedding in browser • Basic syntax • Strings and regular expressions • Functions • Objects 5 © 2009 Marty Hall Intro Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 3. Books • JavaScript the Definitive Guide – By David Flanagan, O Reilly. The only really complete reference Flanagan O’Reilly on the JavaScript language. Thorough and well-written. • Makes the global variable blunder when covering Ajax. • JavaScript: The Good Parts – By Douglas Crockford (of JSON and YUI fame), O’Reilly – Outstanding advanced guide to best practices in core JavaScript, especially functions, objects, and regular expressions. Very short. p y , j , g p y • Does not cover Ajax at all. No DOM scripting. “The K&R of JS”. • Pro JavaScript Techniques – By John Resig (of jQ y fame), APress y g ( jQuery ), – Excellent guide to best practices; not a thorough reference • Does not make the global variable blunder when covering Ajax. • DOM Scripting p g – By Jeremy Keith, FriendsOf Press – Focuses on manipulating DOM and CSS 7 • Makes the global variable blunder when briefly covering Ajax. Online References • JavaScript tutorial (language syntax) • http://www w3schools com/js/ http://www.w3schools.com/js/ • http://developer.mozilla.org/en/docs/ Core_JavaScript_1.5_Guide • JavaScript API references (builtin objects) • http://www.w3schools.com/jsref/ • http://www.devguru.com/technologies/ecmascript/ QuickRef/ • http://www.devguru.com/technologies/JavaScript/ • http://www.javascriptkit.com/jsref/ • http://developer.mozilla.org/en/docs/ Core_JavaScript_1.5_Reference • HTML DOM reference (with JavaScript Examples) • http://www.w3schools.com/htmldom/dom_reference.asp • Official ECMAScript specification • http://www.ecma-international.org/publications/standards/ 8 Ecma-262.htm
  • 4. Firebug • Install Firebug in Firefox – http://getfirebug.com/ • Use Firebug console for interactive testing – h // fi b http://getfirebug.com/cl.html / lh l • Can also use Firebug Lite in Internet Explorer – Not great, but better than nothing p g g – http://getfirebug.com/lite.html • See especially “bookmarklet” link • For more details on Firebug usage – See section on Ajax development and debugging tools 9 © 2009 Marty Hall Embedding JavaScript in HTML Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 5. Loading Scripts • script with src • <script src="my-script.js" type="text/javascript"></script> – Purpose • To define functions, objects, and variables. • Functions will later be triggered by buttons, other user events, inline script tags with body content, etc. • script with body content • <script type="text/javascript">JavaScript code</script> – Purpose p • To directly invoke code that will run as page loads – E.g., to output HTML content built by JavaScript • Don’t use this approach for defining functions or for doing Don t things that could be done in external files. – Slower (no browser caching) and less reusable 11 Example (phish.js) function getMessage() { var amount = Math round(Math random() * 100000); Math.round(Math.random() var message = "You won $" + amount + "!n" + "To collect your winnings, send y y g , your credit cardn" + "and bank details to oil-minister@phisher.com."; return(message); “alert” pops up dialog box } function showWinnings1() { alert(getMessage()); } “document.write” iinserts text into page at current llocation “d t it ” t t ti t t t ti function showWinnings2() { document.write( <h1><blink> document write("<h1><blink>" + getMessage() + "</blink></h1>"); } 12
  • 6. Example (loading-scripts.html) <!DOCTYPE ...><html xmlns="http://www.w3.org/1999/xhtml"> <head><title>Loading Scripts</title> ... Loads script from previous page <script src="./scripts/phish.js" type="text/javascript"></script> </head> <body> Calls showWinnings1 when user presses ... button. Puts result in dialog box. <input type="button" value="How Much Did You Win?" onclick='showWinnings1()'/> ... <script type="text/javascript">showWinnings2()</script> ... </body></html> / / Calls showWinnings2 when page is loaded in browser. Puts result at this location in page. 13 Example (Results) 14
  • 7. Loading Scripts: Special Cases • Internet Explorer bug – Scripts with src fail to load if you use <script.../>. • You must use <script src="..." ...></script> • XHTML: Scripts with body content – It is an error if the body of the script contains special XML characters such as & or < h t h – E.g. <script...>if (a<b) { this(); } else { that(); }</script> – So use CDATA section unless body content is simple So, and clearly has no special characters • <script type="text/javascript"><![CDATA[ JavaScript Code ]]></script> 15 © 2009 Marty Hall Basic Syntax Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 8. Variables • Introduce with “var” – For global variables (!) and local variables. – No “var” for function arguments • You do not declare types – Some people say JavaScript is “untyped” language, but really it is “dynamically typed” language y y y yp g g – JavaScript is very liberal about converting types • There are only two scopes – Global scope • Be very careful with this when using Ajax. • Can cause race conditions conditions. – Function (lexical) scope 17 – There is not block scope as in Java Operators and Statements • Almost same set of operators as Java – + (addition and String concatenation) -, * / concatenation), *, – &&, ||, ++, --, etc – The == comparison is more akin to Java's "equals" – The === operator (less used) is like Java s == Java's • Statements – Semicolons are technically optional • But highly recommended – Consider • return x • return x • They are not identical! The second one returns, then evaluates x. You should act as though semicolons are required as in Java. • Comments – Same as in Java (/* ... */ and // ...) 18
  • 9. Conditionals and Simple Loops • if/else – Almost identical to Java except test can be converted to true/false instead of strict true/false • “false”: false, null undefined "" (empty string), 0 NaN false : false null, undefined, string) 0, • “true”: anything else (including the string “false”) • Basic for loop – Identical to Java except for variable declarations • for(var i=0; i<someVal; i++) { doLoopBody(); } • while loop – Same as Java except test can be converted to boolean • while(someTest) { doLoopBody(); } • do/while loop 19 – Same as Java except test can be converted to boolean Array Basics • One-step array allocation – var primes = [2, 3, 5, 7, 11, 13]; – var names = ["Joe", "Jane", "John", "Juan"]; • No trailing comma after last element (see later slide) • Two-step array allocation – var names = new Array(4); y( ); names[0] = "Joe"; ... names[3] = "Juan"; Juan ; • Indexed at 0 as in Java – for(var i=0; i<names.length; i++) { o (va 0; a es. e gt ; ) doSomethingWith(names[i]); } 20
  • 10. Other Conditionals and Loops • switch – Differs from Java in two ways • The “case” can be an expression • Values need not be ints (compared with ===) ) • for/in loop – On surface, looks similar to Java for/each loop, but • For arrays, values are array indexes, not array values – Use this loop for objects (to see property names), not arrays! Fails with Prototype or other extended arrays • For objects, values are the property names – var names = ["Joe", "Jane", "John", "Juan"]; for(var i in names) { doSomethingWith(names[i]); } 21 More on Arrays • Arrays can be sparse – var names = new A Array(); () names[0] = "Joe"; names[100000] = "Juan"; • Arrays can be resized – Regardless of how arrays is created, you can do: • myArray.length = someNewLength; • myArray[anyNumber] = someNewValue; • myArray.push(someNewValue) – These are legal regardless of which way myArray was made g g y y y • Arrays have methods – push, pop, join, reverse, sort, concat, slice, splice, etc. • See API reference • Regular objects can be treated like arrays 22 – You can use numbers (indexes) as properties
  • 11. Arrays Example function arrayLoops() { var names = ["Joe", "Jane", "John"]; printArray1(names); printArray2(names); names.length = 6; printArray1(names); printArra 1(names) printArray2(names); } function printArray1(array) { for(var i=0; i<array.length; i++) { console.log("[printArray1] array[%o] is %o", i, array[i]); } } console.log is a printf-like way to print output in Firebug function printArray2(array) { Console window. For testing/debugging only. for(var i in array) { console.log("[printArray2] array[%o] is %o", i, array[i]); } Direct call for interactive testing in Firebug console. } (Cut/paste all code into console command line.) 23 arrayLoops(); Array Performance Time to create and sum array of 16 million random numbers 9 8 7 6 5 4 3 2 1 0 JavaScript: p Firefox 3 JavaScript: Google Chrome Java: 1.6_0_10 Note: Internet Explorer 7 was more than 10 times slower than Firefox, so times are not shown here. 24 Source code for benchmarks is in downloadable Eclipse project at coreservlets.com.
  • 12. The Math Class • Almost identical to Java – Like Java, static methods (Math.cos, Math.random, etc.) – Like Java, logs are base e, trig functions are in radians • Functions – Math.abs, Math.acos, Math.asin, Math.atan, Math.atan2, Math.ceil, Math.cos, Math.exp, Math.floor, Math.log, , , p, , g, Math.max, Math.min, Math.pow, Math.random, Math.round, Math.sin, Math.sqrt, Math.tan • Constants – Math.E, Math.LN10, Math.LN2, Math.LOG10E, Math.PI, Math.SQRT1_2, Math.SQRT2 Math.SQRT1 2, 25 © 2009 Marty Hall Strings and Regular Expressions g p Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 13. String Basics • You can use double or single quotes – var names = [ Joe , 'Jane', "John", 'Juan']; ["Joe" Jane John Juan ]; • You can access length property – E.g., "foobar".length returns 6 • N b Numbers can b converted to strings be t dt t i – Automatic conversion during concatenations. String need not be first as in Java • var val = 3 + "abc" + 5; // Result is "3abc5" abc 3abc5 – Conversion with fixed precision • var n = 123.4567; var val = n.toFixed(2); // Result is 123.46 (not 123.45) ( ); ( ) • Strings can be compared with == – "foo" == 'foo' returns true • Strings can be converted to numbers – var i = parseInt("37 blah"); // Result is 37 – ignores blah – var d = parseFloat("6.02 blah"); // Ignores blah 27 Core String Methods • Simple methods similar to Java – charAt, indexOf, lastIndexOf, substring, toLowerCase, toUpperCase • Methods that use regular expressions – match, replace, search, split • HTML methods – anchor, big, bold, fixed, fontcolor, fontsize, italics, link, small, strike, sub, sup • "test".bold().italics().fontcolor("red") returns '<font color="red"><i><b>test</b></i></font>' – These are technically nonstandard methods, but supported y pp in all major browsers • But I prefer to construct HTML strings explicitly anyhow 28
  • 14. Regular Expressions • You specify a regexp with /pattern/ – N with a String as in Java Not i h S i i J • Most special characters same as in Java/Unix/Perl – ^, $, . , , – beginning, end of string, any one char g g, g, y – – escape what would otherwise be a special character – *, +, ? – 0 or more, 1 or more, 0 or 1 occurrences – {n}, {n } {n} {n,} – exactly n, n or more occurrences n – [] – grouping – s, S – whitespace, non-whitespace – w, w W – word char (letter or number), non-word char number) non word • Modifiers – /pattern/g – do global matching (find all matches, not just first one) – /pattern/i – do case-insensitive matching – /pattern/m – do multiline matching 29 Regular Expression: Examples 30
  • 15. More Information on Regular Expressions • Online API references given earlier (See R E (S RegExp class) l ) – http://www.w3schools.com/jsref/jsref_obj_regexp.asp – http://www devguru com/technologies/ecmascript/ http://www.devguru.com/technologies/ecmascript/ QuickRef/regexp.html • JavaScript Regular Expression Tutorials p g p – http://www.evolt.org/article/Regular_Expressions_in_ JavaScript/17/36435/ – h // http://www.javascriptkit.com/javatutors/re.shtml j i ki /j / h l 31 © 2009 Marty Hall Functions “It is Lisp in C s clothing.” It C’s clothing. - JSON and YUI guru Douglas Crockford, describing the JavaScript language in JavaScript: The Good Parts. Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 16. Overview • Not similar to Java –J S i f JavaScript functions very diff i different f from J Java methods h d • Main differences from Java – You can have global functions • Not just methods (functions as part of objects) – You don’t declare return types or argument types – Caller can supply any number of arguments • Regardless of how many arguments you defined – Functions are first-class datatypes • Y can pass f You functions around, store them in arrays, etc. ti d t th i t – You can create anonymous functions (closures) • Critical for Ajax • These are equivalent – function foo(...) {...} 33 – var foo = function(...) {...} Passing Functions: Example function third(x) { return(x / 3); } function triple(x) { return(x * 3); ( ) } function nineTimes(x) { return(x * 9); etu ( ); } Function as argument. function operate(f) { var nums = [1, 2, 3]; for(var i=0; i<nums.length; i++) { var num = nums[i]; console.log( Operation console log("Operation on %o is %o ", %o. num, f(num)); } 34 }
  • 17. Anonymous Functions • Anonymous functions (or closures) let you capture local variables inside a function – You can't do Ajax without this! • Basic anonymous function – operate(function(x) { return(x * 20); }); • Outputs 20, 40, 60 • The "operate" function defined on previous page • Anonymous f function with captured data – function someFunction(args) { var val = someCalculation(args); return(function(moreArgs) { doSomethingWith(val, moreArgs); }); } var f1 = someFunction(args1); var f2 = someFunction(args2); f1(args3); // Uses one copy of "val" 35 f2(args3); // Uses a different copy of "val" Anonymous Functions: Example function multiplier(m) { return(function(x) { return(x * m); }); } function operate2() { var nums = [1, 2, 3]; var functions = [multiplier(1/3), multiplier(3), multiplier(9)]; for(var i=0; i<functions.length; i++) { for(var j=0; j<nums.length; j++) { var f = functions[i]; var num = nums[j]; console.log("Operation on %o is %o.", g p num, f(num)); } } 36 }
  • 18. Optional Args: Summary • Fixed number of optional args – Functions can always be called with any number of args – Compare typeof args to "undefined" – See next page and upcoming convertString function • Arbitrary args – Discover number of args with arguments length arguments.length – Get arguments via arguments[i] – See next page and upcoming longestString function • Optional args via anonymous object – Caller always supplies same number of arguments, but one of the arguments is an anonymous (JSON) object f th t i bj t • This object has optional fields 37 – See later example in “Objects” section Optional Args: Details • You can call any function with any number of arguments f – If called with fewer args, extra args equal "undefined" • You can use typeof arg == "undefined" for this undefined – You can also use boolean comparison if you are sure that no real value could match (e.g., 0 and undefined both return true for !arg) • Use comments to indicate optional args – function foo(arg1, arg2, /* Optional */ arg3) {...} – If called with extra args, you can use “arguments” array • R Regardless of d fi d variables, arguments.length t ll dl f defined i bl t l th tells you how many arguments were supplied, and arguments[i] returns the designated argument • Use comments to indicate extra args – function bar(arg1, arg2 /* varargs */) { ... } 38
  • 19. Optional Arguments function convertString(numString, /* Optional */ base) { if (typeof base == "undefined") { undefined ) base = 10; } var num = parseInt(numString, base); console.log("%s base %o equals %o base 10.", numString, base, num); } 39 Varargs function longestString(/* varargs */) { var longest = "";; for(var i=0; i<arguments.length; i++) { var candidateString = arguments[i]; if (candidateString length > longest length) { (candidateString.length longest.length) longest = candidateString; } } return(longest); } longestString("a", "bb", "ccc", "dddd"); // Returns "dddd" 40
  • 20. © 2009 Marty Hall Objects Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Basics • Constructors –F Functions named for class names. Then use “ i df l Th “new”. ” • No separate class definition! No “real” OOP in JavaScript! – Can define properties with “this” • You must use “this” for properties used in constructors function MyClass(n1) { this.foo = n1; } var m = new MyClass(10); • P Properties (instance variables) ti (i t i bl ) – You don’t define them separately • Whenever you refer to o e, Ja aSc pt just c eates it e e e ee one, JavaScript creates t m.bar = 20; // Now m.foo is 10 and m.bar is 20 • Usually better to avoid introducing new properties in outside code and instead do entire definition in constructor • Methods – Properties whose values are functions 42
  • 21. Objects: Example (Circle Class) function Circle(radius) { this.radius this radius = radius; this.getArea = function() { return(Math.PI * this.radius * this.radius); }; } var c = new Circle(10); c.getArea(); // Returns 31 1 92 () 314.1592... 43 The prototype Property • In previous example –E Every new Circle got its own copy of radius Ci l i f di • Fine, since radius has per-Circle data – Every new Circle got its own copy of getArea function • Wasteful since function definition never changes • Class-level properties – Classname prototype propertyName = value; Classname.prototype.propertyName • Methods – Classname.prototype.methodName = function() {...}; • Just a special case of class-level properties – This is legal anywhere, but it is best to do it in constructor • Pseudo-Inheritance Pseudo Inheritance – The prototype property can be used for inheritance 44 – But complex. See later section on Prototype library
  • 22. Objects: Example (Updated Circle Class) function Circle(radius) { this.radius this radius = radius; Circle.prototype.getArea = function() { return(Math.PI * this.radius * this.radius); }; } var c = new Circle(10); c.getArea(); // Returns 31 1 92 () 314.1592... 45 Rolling Your Own Namespace • Idea –HHave related f l d functions that do not use object properties i h d bj i – You want to group them together and call them with Utils.func1, Utils.func2, etc. • Grouping is a syntactic convenience. Not real methods. • Helps to avoid name conflicts when mixing JS libraries – Similar to static methods in Java • Syntax – Assign functions to properties of an object, but do not define a constructor. E.g., constructor E g • var Utils = {}; // Or "new Object()", or make function Utils Utils.foo = function(a, b) { … }; Utils.bar function(c) { … } Util b = f ti ( ) }; var x = Utils.foo(val1, val2); 46 var y = Utils.bar(val3);
  • 23. Static Methods: Example (Code) var MathUtils = {}; MathUtils.fact = function(n) { if (n <= 1) { return(1); } else { return(n * MathUtils.fact(n-1)); } }; MathUtils.log10 = function(x) { return(Math.log(x)/Math.log(10)); ( g( ) g( )) }; 47 Namespaces in Real Applications • Best practices in large projects – In many (most?) large projects, all global variables (including functions!) are forbidden due to the possibility of name collisions from pieces made by different authors. – So, these primitive namespaces play the role of Java’s packages. Much weaker, but still very valuable. • Fancy variation: repeat the name • var MyApp = {}; • MyApp foo = function foo( ) { … }; MyApp.foo foo(…) • MyApp.bar = function bar(…) { … }; – The name on the right does not become a global name. The l d t Th only advantage is for debugging i f d b i • Firebug and other environments will show the name when 48 you print the function object.
  • 24. JSON (JavaScript Object Notation) • Idea – A simple textual representation of JavaScript objects – Main applications • One time use objects (rather than reusable classes) One-time-use • Objects received via strings • Directly in JavaScript – var someObject = { property1: value1, property2: value2, ... }; • In a string (e.g., when coming in on network) – Surround object representation in parens – Pass to the builtin “eval” function 49 JSON: Example var person = { firstName: 'Brendan',, lastName: 'Eich', bestFriend: { firstName: 'Chris', lastName: 'Wilson' }, greeting: function() { return("Hi, I am " + this.firstName + " " + this.lastName + "."); } }; 50
  • 25. Using JSON for Optional Arguments • Idea – Caller always supplies same number of arguments, but one of the arguments is an anonymous (JSON) object • This object has optional fields – This approach is widely used in Prototype, Scriptaculous, and other JavaScript libraries • Example (a/b: required, c/d/e/f: optional) – someFunction(1.2, 3.4, {c: 4.5, f: 6.7}); – someFunction(1.2, 3 4 someFunction(1 2 3.4, {c: 4.5, d: 6.7, e: 7.8}); 45 6 7 7 8}); – someFunction(1.2, 3.4, {c: 9.9, d: 4.5, e: 6.7, f: 7.8}); – someFunction(1.2, 3.4); ( , ); 51 Using JSON for Optional Arguments: Example Code function sumNumbers(x, y, extraParams) { var result = x + y; if (isDefined(extraParams)) { if (isTrue(extraParams.logInput)) { console.log("Input: x=%s, y=%s", x, y); } if (isDefined(extraParams.extraOperation)) { result = extraParams.extraOperation(result); } } return(result) } function isDefined(value) { return(typeof value != "undefined"); } function isTrue(value) { return(isDefined(value) && (value == true)) 52 }
  • 26. Using JSON for Optional Arguments: Example Results 53 Internet Explorer and Extra Commas • Firefox tolerates trailing commas in both arrays and JSON d • var nums = [1, 2, 3, ]; • var obj = { firstName: "Joe", lastName: "Hacker", }; Joe , Hacker , • IE will crash in both cases. – And, since it is not technically legal anyway, you should write it without commas after the final element: • var nums = [1, 2, 3]; • var obj = { firstName: "Joe", lastName: "Hacker"}; Joe , Hacker }; – This issue comes up moderately often, especially when building JavaScript data on the server, as we will do in upcoming lectures. i l t 54
  • 27. Other Object Tricks • The instanceof operator –D Determines if lhs is a member of class on rhs i lh i b f l h • if (blah instanceof Array) { doSomethingWith(blah.length); } • The typeof operator – Returns direct type of operand, as a String • "number", "string", "boolean", "object", "function", or "undefined". – Arrays and null both return "object" • Adding methods to builtin classes g String.prototype.describeLength = function() { return("My length is " + this.length); }; "Any Random String".describeLength(); • eval – Takes a String representing any JavaScript and runs it • eval("3 * 4 + Math.PI"); // Returns 15.141592 55 © 2009 Marty Hall Wrap-up Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 28. Summary • Use Firebug for testing and debugging • B k Bookmark references k f – http://www.w3schools.com/js/ • Embedding in browser – <script src="blah.js" type="test/javascript"></script> • Basic syntax – Mostly similar to Java • Functions – Totally different from Java. Passing functions around and Java making anonymous functions very important. • Objects – Constructor also defines class. Use “this”. – Totally different from Java. Not like classical OOP at all. 57 © 2009 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.