KEMBAR78
JavaScript Misunderstood | PPT
JavaScript : Misunderstood



                        Bhavya Siddappa
            www.bhavyavoice.blogspot.com
Agenda

   Introduction
   Best practices
   Some cool stuff
   Conclusions
The world’s most misunderstood
language
   The name
       it is originally called LiveScript
       JavaScript is not a subset of Java nor interpreted version of
        Java
   Too many versions
       ECMA committee
   Bad official specification
   Bad reputation – broken language?
       Lousy implementation: Browsers do suck Implementations
        of CSS, events, ... broken Language itself is pretty reliable
       Blame IE
JavaScript bad parts
   Design errors
       overloading of +, clobbered global variables,
        semicolon insertion...
       24.88 + 4.35 -> 29.229999999999997
       0 0.0 ”0” “0.0” null undefined are all false
       0.0 + ”0” -> ”00”
       No class public private keywords
       No package keyword either

   How does this work anyway?
JavaScript Good parts
   Most used scripting language
     Every browser, many OSes(Windows, Dashboard), XUL(Mozilla),

       Flash(ActionScript), Server-side(Phobos, ASP, Rhino), ...
   Great for UI-coding
   Flexible and powerful
     OO, functional

     Closures + Anonymous functions

     Everything is an object (including functions)

     Prototype-based inheritance



   AJAX makes it a must-know

               JavaScript can be used to do good stuff
Agenda

   Introduction
   Best practices
   Some cool stuff
   Conclusions
Always use 'var'
   Keep your scopes straight with var keyword
       Global scope
       Function scope
            var i=0; // Global variable
            function test() {
            for (i=0; i<10; i++) {
            alert("Hello World!");
            }
            }
            test();
            alert(i); // i is ???
Always use 'var'

   Keep your scopes straight with var keyword
       Global scope
       Function scope

            function test() {
            for (var i=0; i<10; i++) {
            alert("Hello World!");
            }
            }
            // i is 10
Pervasive Scope
     var x= 9;
     function foo() {
     alert(x);
     var x = 10;
     alert(x);
     };
     foo();

   Result : ???
Pervasive Scope
          var x= 9;
          function foo() {
          alert(x);
          var x = 10;
          alert(x);
          };
          foo();
   Result: undefined; 10;
   Expected: 9; 10;
Detect Features, Not Browser

if (document.getElementById)
{
    var element =
         document.getElementById ('MyId');
}
else
{
     alert(“ Your Browser lacks the capabilities
           required to run this script !”);
}
Test For an Element's Existence


if ("innerHTML" in document.getElementById("someDiv"))

{

       // code that works with innerHTML

}
Don't Make Assumptions

   NEVER rely on JavaScript
   Don't expect JavaScript to be available but
    make it a nice-to-have rather than a
    dependency
   Expect other scripts to try to interfere with
    your functionality and keep the scope of your
    scripts as secure as possible.
   Ex. JavaScript is enabled but is blocked by a
    firewall or security policy
Don't use with()
with (document.forms["mainForm"].elements)

{                                                      Bad
input1.value = "junk";
input2.value = "junk";
}


                         var elements =
                         document.forms["mainForm"].elements;
                         elements.input1.value = "junk";
                         elements.input2.value = "junk";
    Good
Eval is Evil

   Most powerful and possibly most misused
    method in JavaScript
   Like...
    “swatting a fly with a sledgehammer”
   Every time eval() called, compilation occurs
   When is it ok? Math expressions,
    serialization, dynamic loading of code
Release Objects When Done

   Ex. Initialization Function

    var foo = function()
    {
    // code that makes this function work
    delete foo;
    }
    window.addEventListener('load', foo, false);
Square Bracket Notation
   Dot notation: MyObject.property
   Bracket notation: MyObject[“property”]
    MyObject[“value”+i] OK!
    MyObject.value+i Fail!

 Forms
document.forms["formname"].elements["inputname"]
  OK!
document.formname.inputname Bad!
Unobtrusive JavaScript

   We separate Presentation (CSS) from Content
    (XHTML)
   We separate Behavior (JS) from Content
   Place CSS and JavaScript in separate files
   Dynamically add behavior instead of hard-
    coding
Unobtrusive JavaScript
   Bad
<a href="JavaScript:alert('You clicked!')">Click Me!</a>
<a href="#" onclick="alert('You clicked!')">Click Me!</a>



   OK
     <a href="clicked.html" onclick="alert('You clicked!')">
                        Click Me </a>

   Good
        var div = document.getElementById('clickMe');
       div.onclick = new Function("processClick(this)");
      <a id=”clickMe” href=”clicked.html”>Click Me!</a>
Use Object Oriented JavaScript

   Better reusability and organization
   Allows for dynamic loading of objects
   Write in a style more familiar to Java
    programmers
Object Oriented Example
function Cart() {
this.items = [];
}
function Item (id,name,desc,price) {
this.id = id;
this.name = name;
this.desc = desc;
this.price = price;
}
var cart = new Cart();
cart.items.push(new Item("id-1","Paper","something you write on",5));
cart.items.push(new Item("id-2","Pen", "Something you write with",3));
var total = 0;
for (var l == 0; l < cart.items.length; l++ )
{

    total = total + cart.items[l].price;
}
Use Object Hierarchies

   In JavaScript names may collide
       In Java we have packages to prevent this
   JavaScript does not have packages
       You can use JavaScript objects to organize related
        objects and prevent naming collisions.
Object Hierarchies Example
// create the base BLUEPRINTS object if it does not exist.
if (!BLUEPRINTS) {
var BLUEPRINTS = new Object();
}
// define Cart under BLUEPRINTS
BLUEPRINTS.Cart = function () {
this.items = [];
this.addItem = function(id, qty) {
this.items.push(new Item(id, qty));
}
function Item (id, qty) {
this.id = id;
this.qty = qty;
}
}
// create an instance of the cart and add an item
var cart = new BLUEPRINTS.Cart();
cart.addItem("id-1", 5);
cart.addItem("id-2", 10);
Use the Prototype Property

   Use to define shared behavior and to extend
    objects
   The prototype property is a feature of the
   JavaScript language
       The property is available on all objects
Prototype Property Example
function Cart() {
this.items = [ ];
}
function Item (id,name,desc,price)) {
this.id = id;
this.name = name;
this.desc = desc;
this.price = price;
}
//SmartCart extends the Cart object inheriting its
properties and adds a total property
Function SmartCart() {
this.total = 0;
}
SmartCart.prototype = new Cart();
Object Literals

   Object literals are objects defined using
    braces that contain a set of comma separated
    key/value pairs, similar to a map in Java
   Example
       {key1: “stringValue”, key2: 2, key3: ['blue',
        'yellow']
   Object literals can be used as parameters
   Don't confuse them with JSON, which has a
    similar syntax
Reduce the Size of JavaScript File
   Remove the whitespace and shorten the
    name of variables and functions in a file
   While developing, don't compress so that
    debugging is easier
   When ready to deploy, consider compressing
    your JavaScript files
   Use minimized (compressed) versions of 3rd
    party libraries when available
   Example tool for compression: ShrinkSafe
Agenda

   Introduction
   Best practices
   Some cool stuff
   Conclusions
JSON

   Becoming de-facto standard in transferring
    information for AJAX applications
   Allows us to make cross-domain requests if
    server supports it
   Perfect for serializing JavaScript objects
Getters and Setters in JavaScript 1.5
Technology
   Define functions to be invoked when a
    property is accessed
   Transparent to the client
     var squareProto = {
     side: 0,
     get area()
     { return this.side * this.side; }
     };
     var mySquare = object(squareProto);
     mySquare.side = 5;
     ⊳ mySquare.area - > 25
OpenSocial

   Common social networking API
   Write apps that work with any OpenSocial
    enable website
   Develop OpenSocial apps using only
    JavaScript, HTML, and CSS
Zembly

   Build widgets, applications with JavaScript,
    HTML and CSS
   OpenSocial soon!
   Now publicly available, go try it out, win a
    prize!
Agenda

   Introduction
   Best practices
   Some cool stuff
   Conclusions
Conclusions

   Take time to learn JavaScript and use best
    practices
   Prototype-based object system with object()
   Learn from the masters
   Let NetBeans help you!

JavaScript Misunderstood

  • 1.
    JavaScript : Misunderstood Bhavya Siddappa www.bhavyavoice.blogspot.com
  • 2.
    Agenda  Introduction  Best practices  Some cool stuff  Conclusions
  • 3.
    The world’s mostmisunderstood language  The name  it is originally called LiveScript  JavaScript is not a subset of Java nor interpreted version of Java  Too many versions  ECMA committee  Bad official specification  Bad reputation – broken language?  Lousy implementation: Browsers do suck Implementations of CSS, events, ... broken Language itself is pretty reliable  Blame IE
  • 4.
    JavaScript bad parts  Design errors  overloading of +, clobbered global variables, semicolon insertion...  24.88 + 4.35 -> 29.229999999999997  0 0.0 ”0” “0.0” null undefined are all false  0.0 + ”0” -> ”00”  No class public private keywords  No package keyword either  How does this work anyway?
  • 5.
    JavaScript Good parts  Most used scripting language  Every browser, many OSes(Windows, Dashboard), XUL(Mozilla), Flash(ActionScript), Server-side(Phobos, ASP, Rhino), ...  Great for UI-coding  Flexible and powerful  OO, functional  Closures + Anonymous functions  Everything is an object (including functions)  Prototype-based inheritance  AJAX makes it a must-know JavaScript can be used to do good stuff
  • 6.
    Agenda  Introduction  Best practices  Some cool stuff  Conclusions
  • 7.
    Always use 'var'  Keep your scopes straight with var keyword  Global scope  Function scope var i=0; // Global variable function test() { for (i=0; i<10; i++) { alert("Hello World!"); } } test(); alert(i); // i is ???
  • 8.
    Always use 'var'  Keep your scopes straight with var keyword  Global scope  Function scope function test() { for (var i=0; i<10; i++) { alert("Hello World!"); } } // i is 10
  • 9.
    Pervasive Scope var x= 9; function foo() { alert(x); var x = 10; alert(x); }; foo();  Result : ???
  • 10.
    Pervasive Scope var x= 9; function foo() { alert(x); var x = 10; alert(x); }; foo();  Result: undefined; 10;  Expected: 9; 10;
  • 11.
    Detect Features, NotBrowser if (document.getElementById) { var element = document.getElementById ('MyId'); } else { alert(“ Your Browser lacks the capabilities required to run this script !”); }
  • 12.
    Test For anElement's Existence if ("innerHTML" in document.getElementById("someDiv")) { // code that works with innerHTML }
  • 13.
    Don't Make Assumptions  NEVER rely on JavaScript  Don't expect JavaScript to be available but make it a nice-to-have rather than a dependency  Expect other scripts to try to interfere with your functionality and keep the scope of your scripts as secure as possible.  Ex. JavaScript is enabled but is blocked by a firewall or security policy
  • 14.
    Don't use with() with(document.forms["mainForm"].elements) {  Bad input1.value = "junk"; input2.value = "junk"; } var elements = document.forms["mainForm"].elements; elements.input1.value = "junk"; elements.input2.value = "junk";  Good
  • 15.
    Eval is Evil  Most powerful and possibly most misused method in JavaScript  Like... “swatting a fly with a sledgehammer”  Every time eval() called, compilation occurs  When is it ok? Math expressions, serialization, dynamic loading of code
  • 16.
    Release Objects WhenDone  Ex. Initialization Function var foo = function() { // code that makes this function work delete foo; } window.addEventListener('load', foo, false);
  • 17.
    Square Bracket Notation  Dot notation: MyObject.property  Bracket notation: MyObject[“property”] MyObject[“value”+i] OK! MyObject.value+i Fail!  Forms document.forms["formname"].elements["inputname"] OK! document.formname.inputname Bad!
  • 18.
    Unobtrusive JavaScript  We separate Presentation (CSS) from Content (XHTML)  We separate Behavior (JS) from Content  Place CSS and JavaScript in separate files  Dynamically add behavior instead of hard- coding
  • 19.
    Unobtrusive JavaScript  Bad <a href="JavaScript:alert('You clicked!')">Click Me!</a> <a href="#" onclick="alert('You clicked!')">Click Me!</a>  OK <a href="clicked.html" onclick="alert('You clicked!')"> Click Me </a>  Good var div = document.getElementById('clickMe'); div.onclick = new Function("processClick(this)"); <a id=”clickMe” href=”clicked.html”>Click Me!</a>
  • 20.
    Use Object OrientedJavaScript  Better reusability and organization  Allows for dynamic loading of objects  Write in a style more familiar to Java programmers
  • 21.
    Object Oriented Example functionCart() { this.items = []; } function Item (id,name,desc,price) { this.id = id; this.name = name; this.desc = desc; this.price = price; } var cart = new Cart(); cart.items.push(new Item("id-1","Paper","something you write on",5)); cart.items.push(new Item("id-2","Pen", "Something you write with",3)); var total = 0; for (var l == 0; l < cart.items.length; l++ ) { total = total + cart.items[l].price; }
  • 22.
    Use Object Hierarchies  In JavaScript names may collide  In Java we have packages to prevent this  JavaScript does not have packages  You can use JavaScript objects to organize related objects and prevent naming collisions.
  • 23.
    Object Hierarchies Example //create the base BLUEPRINTS object if it does not exist. if (!BLUEPRINTS) { var BLUEPRINTS = new Object(); } // define Cart under BLUEPRINTS BLUEPRINTS.Cart = function () { this.items = []; this.addItem = function(id, qty) { this.items.push(new Item(id, qty)); } function Item (id, qty) { this.id = id; this.qty = qty; } } // create an instance of the cart and add an item var cart = new BLUEPRINTS.Cart(); cart.addItem("id-1", 5); cart.addItem("id-2", 10);
  • 24.
    Use the PrototypeProperty  Use to define shared behavior and to extend objects  The prototype property is a feature of the  JavaScript language  The property is available on all objects
  • 25.
    Prototype Property Example functionCart() { this.items = [ ]; } function Item (id,name,desc,price)) { this.id = id; this.name = name; this.desc = desc; this.price = price; } //SmartCart extends the Cart object inheriting its properties and adds a total property Function SmartCart() { this.total = 0; } SmartCart.prototype = new Cart();
  • 26.
    Object Literals  Object literals are objects defined using braces that contain a set of comma separated key/value pairs, similar to a map in Java  Example  {key1: “stringValue”, key2: 2, key3: ['blue', 'yellow']  Object literals can be used as parameters  Don't confuse them with JSON, which has a similar syntax
  • 27.
    Reduce the Sizeof JavaScript File  Remove the whitespace and shorten the name of variables and functions in a file  While developing, don't compress so that debugging is easier  When ready to deploy, consider compressing your JavaScript files  Use minimized (compressed) versions of 3rd party libraries when available  Example tool for compression: ShrinkSafe
  • 28.
    Agenda  Introduction  Best practices  Some cool stuff  Conclusions
  • 29.
    JSON  Becoming de-facto standard in transferring information for AJAX applications  Allows us to make cross-domain requests if server supports it  Perfect for serializing JavaScript objects
  • 30.
    Getters and Settersin JavaScript 1.5 Technology  Define functions to be invoked when a property is accessed  Transparent to the client var squareProto = { side: 0, get area() { return this.side * this.side; } }; var mySquare = object(squareProto); mySquare.side = 5; ⊳ mySquare.area - > 25
  • 31.
    OpenSocial  Common social networking API  Write apps that work with any OpenSocial enable website  Develop OpenSocial apps using only JavaScript, HTML, and CSS
  • 32.
    Zembly  Build widgets, applications with JavaScript, HTML and CSS  OpenSocial soon!  Now publicly available, go try it out, win a prize!
  • 33.
    Agenda  Introduction  Best practices  Some cool stuff  Conclusions
  • 34.
    Conclusions  Take time to learn JavaScript and use best practices  Prototype-based object system with object()  Learn from the masters  Let NetBeans help you!