JavaScript is a lightweight programming
language to add interactivity to HTML
pages.
 Put

dynamic text into an HTML page.
 React to events
 Read and write HTML elements
 Validate input data
 Detect the visitor's browser
 Create cookies
New in Html 5:
 Access new HTML Elements and Events.
 Draw using canvas object
 Geolocation: get current location position.
 Offline Storage
 Post message
 Multiple Thread
 Socket Programming
 Offline web application
 Embedded

in Html.

<script type="text/javascript"><![CDATA[
JavaScript Code
]]></script>

 Scripts

can be provided locally or remotely.

<script language="JavaScript” type="text/javascript“
src="http://somesite/myOwnJavaScript.js">
</script>
 Variable

scope and declaration.
 Popup Boxes:
alert("sometext")
confirm("sometext")
prompt("sometext","defaultvalue")
 Conditional

statement

• if, if.. else, switch
 Loop

• for loop, while loop
 try...catch
 Throw
 Encapsulate

your code into functions
 Common

Features

• DOM Selector
• DOM modification
• Traversing

• Dynamic Styles
• Events
Compatibility Items:
 Elements
 Attributes
 Browser version
 Device/Operating system
Detect the visitor's browser
var x = "User-agent header sent: " + navigator.userAgent;
User-agent header sent: Opera/9.80 (Windows NT 5.1)
Presto/2.12.388 Version/12.16
var el = document.createElement(“new_el”);
element.appendChild(el);

document.body.appendChild(el);
var fragment = document.createDocumentFragment ();
fragment.appendChild(el_1)
fragment.appendChild(el_2)
fragment.appendChild(el_3)
fragment.appendChild(el_4)

document.body.appendChild(fragment);
var el = document.getElementById(„Id‟);//single element
if (document.all || document.getElementById) {
...
}
val el = document.get ElementsByClassName(„el‟);//select collection of nodes
el[0] //get the first element
val el = document.get ElementsByTagName(„tagName‟);//select collection of
nodes
el[0] //get the first element
val el = document.get ElementsByTagName(„*‟);//select all tags
val el = document.get ElementsByName(„el‟);//select collection of nodes
el[0] //get the first element
var el = document.querySelector(„#Id‟);//select first element
val el = document.querySelector( „.el‟);//select first element
val el = document.querySelectorAll( „.el‟);//select collection of nodes
 Some

old:

• getElementById
• getElementsByTagNameNot work with object
 Some

new:

• getElementsByClassName
 Firefox 3, Safari 3, Opera 9.6, IE9
 Opera doesn’t match a second-specified class
• querySelectorAll
 In Firefox 3.1, Safari 3.1, Opera 10, IE 8
 Safari 3.1 had memory out of bounds problems
 Safari 3.2 can’t match uppercase characters in quirks mode
DOM Collection

links
document.links
document.links[0]

forms

document.forms
document.forms[0]

anchors

document.anhors
document. anhors[0]
element.innerHTML = “HTML code”;
var attributeValue = element.getAttribute(attributeName);
element.setAttribute(attributeName, attributeValue);
element.removeChild(el1);
var el = element.parentNode;
var el = element.childNodes; //Elements + White space
var el = element.children; //Only Elements
var el = element..nextSibling; //next node or null
var el = element..previousSibling; //previous node or null
var el = element..nextElementSibling;
var el = element..previousElementSibling;
 onabort

- Loading of an image is interrupted
 onblur - An element loses focus
 onchange - The content of a field changes
 onclick - Mouse clicks an object
 ondblclick - Mouse double-clicks an object
 onerror - An error occurs when loading a
document or an image
 onfocus - An element gets focus
 onkeydown - A keyboard key is pressed
 onkeypress

- A keyboard key is pressed or

held down
 onkeyup - A keyboard key is released
 onload - A page or an image is finished
loading
 onmousedown - A mouse button is pressed
 onmousemove - The mouse is moved
 onmouseout - The mouse is moved off an
element
 onmouseover - The mouse is moved over an
element
 onmouseup - A mouse button is released
 onreset

- The reset button is clicked
 onresize A window or frame is resized
 onselect - Text is selected
 onsubmit - The submit button is clicked
 onunload - The user exits the page
<img id="myImage"
src="http://3.bp.blogspot.com/_ss1KeGx9Bng/THgWaTaHhuI/AAAAAAAAAB0/3PL
mvniAdNk/s1600/lolcats_oh-noes_ihasletgo.jpg">
<script>
var img = document.getElementById("myImage"),
img2=new Image(),
originalSrc = img.src;

img2.src="https://i.chzbgr.com/maxW500/6073452544/h4B353A81/";
img.onmouseover = function(){
document.getElementById('myImage').src=img2.src;
}

img.onmouseout = function(){
document.getElementById('myImage').src=originalSrc;
}
</script>
// Internet Explorer
element.attachEvent('click',
function() {
alert(window.event);
}
)
// Everyone else
element.addEventListener('click',
function(ev) { alert(ev) }, false
);




Bubbling: the event is first captured and handled by the inner most
element and then propagated to outer elements.
Capturing : event is first captured by the outer most element and
propagated to the inner most element.
Only event bubbling model is supported by all the major browsers.

if ( <addEventListener detect> ) {
// W3C DOM Event Model
// Supported by: Firefox, Chrome, Safari, Opera, and (now) IE9
}
else if ( <IE or attachEvent detect> ) {
// Previous IE Event Model code
}
To preventing any parent event handlers from being executed.

addEvent(div, 'mouseover', function(ev) {event =
event || window.event // cross-browser event
if (event.stopPropagation) {
// W3C standard variant
event.stopPropagation()
} else {
// IE variant
event.cancelBubble = true
}
});
JavaScript is an Object Oriented
Programming (OOP) language
 Primitive

Types
 Reference Types
• Boolean true, false

• Number 1, 3.141, -1.602e-19
• String "Joe"
• null null
• undefined undefined
 Only

one number type
 64 bit floating point
 Does not map well to common
understanding of arithmetic
 0.1 + 0.2 = 0.30000000000000004
 Special

number: Not a Number
 Result of undefined or erroneous
operations.
 Toxic: any arithmetic operation with NaN
will have a NaN as a result.
 NaN is not equal anything including NaN
Number(value)
 Convert the value into a number.
 It produces NaN if it has a problem.
parseInt(value,10)
 Convert the value into a number.
 It stops at the first non-digit character.
 The radix (10) should be required
parseInt(“08”) === 0
parseInt(“08”, 10) === 8












abs absolute value
floor integer
log logarithm
max maximum
pow raise to a power
random random number
round nearest integer
sin
sin
sqrt square root
 Unicode

 String

literals can use single or double
quotes.














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

value that isn’t anything
 Default

value for variables and parameters
 The value of missing members in objects
function isDefined(value) {
return(typeof value != "undefined");
}






Date new Date(1211623944453);
Error new Error("Oops!");
RegExp /^web.*$/i;
Array [ "apple", "banana" ]
Function function(x) {return x*x}
 Date
new Date() ; //Current date
new Date(year, month, day);
Date.parse('2/6/2009');//wrong will depend on culture

 Y2K

Problem

Date.prototype.getRealYear = function()
{
if(this.getFullYear)
return this.getFullYear();
else
return this.getYear() + 1900;
};
unordered collection of properties with
arbitrary values
 object literal
var obj = { name: "Joe", age: 26 };
 setting a property
obj.lastName = "Smith";
 retrieving properties
alert(obj.name + " " + obj.lastName);
Data structure that associates arbitrary
values with arbitrary strings
 property name as an identifier
obj.lastName = "Smith";
 property name as a string
obj["lastName"] = "Smith";
 for( prop in obj ) {
alert( prop + ": " + obj[prop] );
}
Concept of a class does not exist...
... but use a function as a constructor:
 function Dog() {};
class “Dog”
 var lassie = new Dog(); instance “lassie”
 alert(lassie instanceof Dog); // true
Because functions are „first-class objects“
we can attach properties:
 Class Variables
Dog.SPECIES = "Canis lupus";
 Class Methods
Dog.getCount = function() {
return Dog.COUNT;
};
 Instance

Variables
function Dog(name) {
this.name = name;
};
var lassie = new Dog("Lassie");
alert( lassie.name );
 Instance

Methods
function Dog(name) {
this.name = name;
this.bark =
function() { alert("Woof!") };
};
var lassie = new Dog("Lassie");
lassie.bark();
 Global

Scope

• Variables outside of any functions
• Variables inside functions without var

var global1 = 1;
global2 = 2;
function foo() {
global3 = 3;
};
 Function

Scope

• Variables inside functions declared with var
• Function arguments
function foo(local1) {
var local2 = 2;
};
 Block

Scope
... but can be faked:
// before block
(function() {
// inside block
})();
// after block
function Dog(name) {
var _name = name; // private variable
// privileged method
this.getName = function() {
return _name;
};
};
var lassie = new Dog("Lassie");
alert( lassie.getName() );
function Dog(name) {
var _name = name;
// private method
var _fixName = function() {
return _name.toUpperCase();
};
this.getName = function(){
return _fixName();
};
};
 Nested

functions
 Inner function has still access to local
 variables even after the outer function
 has finished
function outer()
{
var count = 1;
function inner() { alert(count++) }
return inner;
}
var myClosure = outer();
myClosure(); // ==> 1
myClosure(); // ==> 2
 function

Pet() {};
Pet

 function

Dog() {};

 Dog.prototype

= new Pet;
Dog
function Pet(name) {
this.name = name;
};
function Dog(name) {
// super(name)
Pet.call( this, name );
this.bark = function() {};
};
Dog.prototype = new Pet;
 //

old: attach to "this“

function Dog(name) {
this.bark =
function(){ alert("Woof!") };
};

 //

new: attach to "prototype"

function Dog(name) {};
Dog.prototype.bark =
function(){ alert("Woof!") };
};
 Property

values on instance:
 local, instance-specific values
 Property values on prototype:
 read-only default values attaching to the
prototype saves memory, especially for
large numbers of instances
 Affects

all new instances
 Affects all existing instances
 Allows modification of existing classes
String.prototype.trim =
function() {
return this.replace(/^s+/, "");
};
alert(" Lassie".trim() );
function Dog() {};
Dog.prototype.bark =
function() { alert("Woof!") };
function Bulldog() {};
Bulldog.prototype = new Dog;
Bulldog.prototype.bark = function() {
// super.bark();
Dog.prototype.bark.call(this);
alert("Grrrh!!") };
function Pet() {
if(this._id == Pet._id) {
throw new Error("No Pets, please!");
}
}
Pet._id = "Pet";
Pet.prototype._id = "Pet";
var fiffy = new Pet; // Error (intended)
But now our code to setup inheritance will
fail:
Dog.prototype = new Pet; // Error :-(
Solution: Do not create an instance of the
actual
superclass just to setup inheritance, use a
dummy:
function Dummy() {};
Dummy.prototype = Pet.prototype;
Dog.prototype = new Dummy;
if (typeof very == "undefined") {
very = {};
}
if (typeof very.cute == "undefined") {
very.cute = {};
}
very.cute.Dog = function() {};
var fiffy = new very.cute.Dog;
// The Last of the Mohicans
var chingachgook = {
fight : function() {
alert("Woah!");
}
};
chingachgook.fight();
function Mohican() {
this.fight = function(){alert("Woah!")}
};
Mohican.getInstance = function() {
if (!this._instance) {
this.instance = new this; }
return this._instance;
};
Mohican.getInstance().fight();


Avoiding Conflicts with Other Libraries ($)


<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
var $j = jQuery.noConflict();
// $j is now an alias to the jQuery function; creating the new alias is optional.
$j(document).ready(function() {
$j( "div" ).hide();
});
// The $ variable now has the prototype meaning, which is a shortcut for
// document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
window.onload = function() {
var mainDiv = $( "main" );
}
</script>


use multiple window.onload events with external scripts:

window.onload = init;
function addOnloadEvent(fnc){
if ( typeof window.addEventListener != "undefined" )
window.addEventListener( "load", fnc, false );
else if ( typeof window.attachEvent != "undefined" ) {
window.attachEvent( "onload", fnc );
}
else {
if ( window.onload != null ) {var oldOnload = window.onload;
window.onload = function ( e ) {oldOnload( e ); window[fnc]();};
}
else
window.onload = fnc;
}
}
addOnloadEvent(myFunctionName);


Feature-Detect Rather Than Browser-Detect

if (document.getElementById) {
var element = document.getElementById('MyId');
}
else {
alert('Your browser lacks the capabilities required to run this script!');
}


Use Square Bracket Notation
MyObject.property
MyObject."value"+I

(Work)
(not Work)

formref.elements.name[] (not Work)

MyObject["property"] (Work)
MyObject["value"+i] (Work)

formref.elements["name[]"] (Work)


Use onclick In Anchors Instead Of javascript: Pseudo-Protocol
<a href="/" onClick="return validate();">Home</a>
function validate() {
return prompt("Are you sure you want to exit this page?");
}



What Not To Do
<a href="javascript:doSomething()">link</a>
<a href="#" onClick="doSomething()">link</a>
<a href="#" onClick="javascript:doSomething();">link</a>
<a href="#" onClick="javascript:doSomething(); return false;">link</a>


Use The Unary + Operator To TypeConvert To Number

function total() {
var theform = document.forms["myform"];
var total = (+theform.elements["val1"].value) + (+theform.elements["val2"].value);
alert(total); // This will alert 3
}


Don't Use HTML Comments In Script Blocks
<script language="javascript">
<!-// code here
//-->
</script>


Avoid Cluttering The Global Namespace

var MyLib = {}; // global Object cointainer
MyLib.value = 1;
MyLib.increment = function() { MyLib.value++; }
MyLib.show = function() { alert(MyLib.value); }
MyLib.value=6;
MyLib.increment();
MyLib.show(); // alerts 7






Model:
organize the application's data layer.
View:
Templates to render HTML data in controllers and inject them into the DOM.
Composed Views: divide the view into small blocks which can be reused or adapted
to different scenarios.
Controller :
A controller is a list of functions that gets called back when the appropriate event
happens.
 Extend

Methods.
 UI Controls and Library.
 Compatibility.
 Performance.
 Jquery

 The

Dojo Toolkit
 The Yahoo! User Interface Library
 Prototype (and Script.aculo.us)
 MooTools
 ExtJS
provides everything you need to build robust
desktop and mobile web apps.
 JavaScriptMVC

 Knockout
 AngularJS
Framework

UI
Bindings

Composed
Views

Web Presentation
Layer

Plays Nicely
With Others

Backbone.js

✗

✗

✓

✓

SproutCore 1.x

✓

✓

✗

✗

Sammy.js

✗

✗

✓

✓

Spine.js

✗

✗

✓

✓

Cappuccino

✓

✓

✗

✗

Knockout.js

✓

✗

✓

✓

Javascript MVC

✗

✓

✓

✓

Google Web
Toolkit

✗

✓

✗

✗

Google Closure

✗

✓

✓

✗

Ember.js

✓

✓

✓

✓

Angular.js

✓

✗

✓

✓

Batman.js

✓

✗

✓

✓




Define local variables
var doc = document;
elem = doc.getElementById(“objId”);
Combine control conditions and control variable changes when using loops
var x = 9;
do { } while( x-- );


Define arrays for HTML collection objects

function array(items) {
try {
return Array.prototype.concat.call(items);
} catch (ex) {
var i = 0, len = items.length, result = Array(len);
while (i < len) { result[i] = items[i];i++; }
return result;
}
}
var divs = array(
document.getElementsByTagName('div') );
for (var i=0l i < divs.length; i++ ) {
var div = document.createElement("div");
document.appendChild(div);
}


Appending DOM elements all at once faster than adding them individually.


var div = document.getElementsByTagName("div");
var fragment = document.createDocumentFragment();
for ( var e = 0; e < elems.length; e++ ) {
fragment.appendChild( elems[e] );
}

for ( var i = 0; i < div.length; i++ ) {
div[i].appendChild( fragment.cloneNode(true) );
}


Change CSS classes not styles


Optimizing Events
<ul id="menu">
<li id="home">Home</li>
<li id="products">Products</li>
<li id="portfolio">Portfolio</li>
<li id="shop">Shop</li>
</ul>
var menuHandler = function(event) {
event = event || window.event;
var target = event.target || event.srcElement;
if (target.id === 'home') {// go home}
}
document.getElementById('menu').addEventListener('cli
ck',menuHandler);


Avoid memory leaks and circular references in your closures

//Classic case for circular references
function foo(e,d) {
$(e).on("click", function() {
//Do something with d
});
}
//Break the cycle!
function foo(e, d) {
$(e).on("click", cbk(d));
}
function cbk (d) {
}





Avoid using eval
Minimize file size
Caching use external file
Deferred execution


Loading on demand
<script src="lab.js"></script>
<script>
$LAB
.script("jquery.js")
.wait()
.script("jquery.color.js")
.script("jquery.otherplugin.js")
.script("mylib.js")
.wait()
.script("unrelated1.js")
.script("unrelated2.js");
</script>




Minimize file size (use minified files)
Deferred execution
 Frame

 Eval
 Html

Encode:

• escape

• encodeURI
• encodeURIComponent
• html.replace(/</g,"&lt;").replace(/>/g,"&gt;")
 Obfuscate

using tool YUI Compressor. Will
it protect javascript?
TOOLS
 Firebug (FF)
 MS Visual Web Developer (IE)
 DragonFly (Opera)
 Chrome
 Drosera / Web Inspector (Safari)
 Console:

http://code.google.com/p/console-js/
http://patik.com/blog/complete-cross-browserconsole-log/
 Dojo

Shrink Safe
http://shrinksafe.dojotoolkit.org/
 YUI
http://refresh-sf.com/yui/
 Dean Edwards Packer / Compress.js
 Yslow

 Firebug
 Chrome's

development tools
 In

browser (easy) - JSUnit
 Browser Control (comprehensive) –
Selenium
http://www.seleniumhq.org/
 Simulated (fast) – Env.js
http://www.envjs.com/
– Understands JavaScript, hard to
document complex features
http://code.google.com/p/jsdoc-toolkit/
 Natural Docs – Can document anything
 MVCDoc – Can document anything,
understands some JS.
 JSDoc

Art of Javascript

  • 2.
    JavaScript is alightweight programming language to add interactivity to HTML pages.
  • 3.
     Put dynamic textinto an HTML page.  React to events  Read and write HTML elements  Validate input data  Detect the visitor's browser  Create cookies
  • 4.
    New in Html5:  Access new HTML Elements and Events.  Draw using canvas object  Geolocation: get current location position.  Offline Storage  Post message  Multiple Thread  Socket Programming  Offline web application
  • 5.
     Embedded in Html. <scripttype="text/javascript"><![CDATA[ JavaScript Code ]]></script>  Scripts can be provided locally or remotely. <script language="JavaScript” type="text/javascript“ src="http://somesite/myOwnJavaScript.js"> </script>
  • 6.
     Variable scope anddeclaration.  Popup Boxes: alert("sometext") confirm("sometext") prompt("sometext","defaultvalue")
  • 7.
     Conditional statement • if,if.. else, switch  Loop • for loop, while loop  try...catch  Throw  Encapsulate your code into functions
  • 9.
     Common Features • DOMSelector • DOM modification • Traversing • Dynamic Styles • Events
  • 10.
    Compatibility Items:  Elements Attributes  Browser version  Device/Operating system Detect the visitor's browser var x = "User-agent header sent: " + navigator.userAgent; User-agent header sent: Opera/9.80 (Windows NT 5.1) Presto/2.12.388 Version/12.16
  • 13.
    var el =document.createElement(“new_el”); element.appendChild(el); document.body.appendChild(el);
  • 14.
    var fragment =document.createDocumentFragment (); fragment.appendChild(el_1) fragment.appendChild(el_2) fragment.appendChild(el_3) fragment.appendChild(el_4) document.body.appendChild(fragment);
  • 15.
    var el =document.getElementById(„Id‟);//single element if (document.all || document.getElementById) { ... } val el = document.get ElementsByClassName(„el‟);//select collection of nodes el[0] //get the first element val el = document.get ElementsByTagName(„tagName‟);//select collection of nodes el[0] //get the first element val el = document.get ElementsByTagName(„*‟);//select all tags val el = document.get ElementsByName(„el‟);//select collection of nodes el[0] //get the first element
  • 16.
    var el =document.querySelector(„#Id‟);//select first element val el = document.querySelector( „.el‟);//select first element val el = document.querySelectorAll( „.el‟);//select collection of nodes
  • 17.
     Some old: • getElementById •getElementsByTagNameNot work with object  Some new: • getElementsByClassName  Firefox 3, Safari 3, Opera 9.6, IE9  Opera doesn’t match a second-specified class • querySelectorAll  In Firefox 3.1, Safari 3.1, Opera 10, IE 8  Safari 3.1 had memory out of bounds problems  Safari 3.2 can’t match uppercase characters in quirks mode
  • 18.
  • 19.
    element.innerHTML = “HTMLcode”; var attributeValue = element.getAttribute(attributeName); element.setAttribute(attributeName, attributeValue);
  • 20.
  • 21.
    var el =element.parentNode; var el = element.childNodes; //Elements + White space var el = element.children; //Only Elements var el = element..nextSibling; //next node or null var el = element..previousSibling; //previous node or null var el = element..nextElementSibling; var el = element..previousElementSibling;
  • 23.
     onabort - Loadingof an image is interrupted  onblur - An element loses focus  onchange - The content of a field changes  onclick - Mouse clicks an object  ondblclick - Mouse double-clicks an object  onerror - An error occurs when loading a document or an image  onfocus - An element gets focus  onkeydown - A keyboard key is pressed
  • 24.
     onkeypress - Akeyboard key is pressed or held down  onkeyup - A keyboard key is released  onload - A page or an image is finished loading  onmousedown - A mouse button is pressed  onmousemove - The mouse is moved  onmouseout - The mouse is moved off an element  onmouseover - The mouse is moved over an element  onmouseup - A mouse button is released
  • 25.
     onreset - Thereset button is clicked  onresize A window or frame is resized  onselect - Text is selected  onsubmit - The submit button is clicked  onunload - The user exits the page
  • 26.
    <img id="myImage" src="http://3.bp.blogspot.com/_ss1KeGx9Bng/THgWaTaHhuI/AAAAAAAAAB0/3PL mvniAdNk/s1600/lolcats_oh-noes_ihasletgo.jpg"> <script> var img= document.getElementById("myImage"), img2=new Image(), originalSrc = img.src; img2.src="https://i.chzbgr.com/maxW500/6073452544/h4B353A81/"; img.onmouseover = function(){ document.getElementById('myImage').src=img2.src; } img.onmouseout = function(){ document.getElementById('myImage').src=originalSrc; } </script>
  • 27.
    // Internet Explorer element.attachEvent('click', function(){ alert(window.event); } ) // Everyone else element.addEventListener('click', function(ev) { alert(ev) }, false );
  • 28.
       Bubbling: the eventis first captured and handled by the inner most element and then propagated to outer elements. Capturing : event is first captured by the outer most element and propagated to the inner most element. Only event bubbling model is supported by all the major browsers. if ( <addEventListener detect> ) { // W3C DOM Event Model // Supported by: Firefox, Chrome, Safari, Opera, and (now) IE9 } else if ( <IE or attachEvent detect> ) { // Previous IE Event Model code }
  • 29.
    To preventing anyparent event handlers from being executed. addEvent(div, 'mouseover', function(ev) {event = event || window.event // cross-browser event if (event.stopPropagation) { // W3C standard variant event.stopPropagation() } else { // IE variant event.cancelBubble = true } });
  • 31.
    JavaScript is anObject Oriented Programming (OOP) language
  • 32.
  • 33.
    • Boolean true,false • Number 1, 3.141, -1.602e-19 • String "Joe" • null null • undefined undefined
  • 34.
     Only one numbertype  64 bit floating point  Does not map well to common understanding of arithmetic  0.1 + 0.2 = 0.30000000000000004
  • 35.
     Special number: Nota Number  Result of undefined or erroneous operations.  Toxic: any arithmetic operation with NaN will have a NaN as a result.  NaN is not equal anything including NaN
  • 36.
    Number(value)  Convert thevalue into a number.  It produces NaN if it has a problem.
  • 37.
    parseInt(value,10)  Convert thevalue into a number.  It stops at the first non-digit character.  The radix (10) should be required parseInt(“08”) === 0 parseInt(“08”, 10) === 8
  • 38.
             abs absolute value floorinteger log logarithm max maximum pow raise to a power random random number round nearest integer sin sin sqrt square root
  • 39.
     Unicode  String literalscan use single or double quotes.
  • 40.
  • 41.
  • 42.
     Default value forvariables and parameters  The value of missing members in objects function isDefined(value) { return(typeof value != "undefined"); }
  • 43.
         Date new Date(1211623944453); Errornew Error("Oops!"); RegExp /^web.*$/i; Array [ "apple", "banana" ] Function function(x) {return x*x}
  • 44.
     Date new Date(); //Current date new Date(year, month, day); Date.parse('2/6/2009');//wrong will depend on culture  Y2K Problem Date.prototype.getRealYear = function() { if(this.getFullYear) return this.getFullYear(); else return this.getYear() + 1900; };
  • 45.
    unordered collection ofproperties with arbitrary values  object literal var obj = { name: "Joe", age: 26 };  setting a property obj.lastName = "Smith";  retrieving properties alert(obj.name + " " + obj.lastName);
  • 46.
    Data structure thatassociates arbitrary values with arbitrary strings  property name as an identifier obj.lastName = "Smith";  property name as a string obj["lastName"] = "Smith";  for( prop in obj ) { alert( prop + ": " + obj[prop] ); }
  • 47.
    Concept of aclass does not exist... ... but use a function as a constructor:  function Dog() {}; class “Dog”  var lassie = new Dog(); instance “lassie”  alert(lassie instanceof Dog); // true
  • 48.
    Because functions are„first-class objects“ we can attach properties:  Class Variables Dog.SPECIES = "Canis lupus";  Class Methods Dog.getCount = function() { return Dog.COUNT; };
  • 49.
     Instance Variables function Dog(name){ this.name = name; }; var lassie = new Dog("Lassie"); alert( lassie.name );
  • 50.
     Instance Methods function Dog(name){ this.name = name; this.bark = function() { alert("Woof!") }; }; var lassie = new Dog("Lassie"); lassie.bark();
  • 51.
     Global Scope • Variablesoutside of any functions • Variables inside functions without var var global1 = 1; global2 = 2; function foo() { global3 = 3; };
  • 52.
     Function Scope • Variablesinside functions declared with var • Function arguments function foo(local1) { var local2 = 2; };
  • 53.
     Block Scope ... butcan be faked: // before block (function() { // inside block })(); // after block
  • 54.
    function Dog(name) { var_name = name; // private variable // privileged method this.getName = function() { return _name; }; }; var lassie = new Dog("Lassie"); alert( lassie.getName() );
  • 55.
    function Dog(name) { var_name = name; // private method var _fixName = function() { return _name.toUpperCase(); }; this.getName = function(){ return _fixName(); }; };
  • 56.
     Nested functions  Innerfunction has still access to local  variables even after the outer function  has finished
  • 57.
    function outer() { var count= 1; function inner() { alert(count++) } return inner; } var myClosure = outer(); myClosure(); // ==> 1 myClosure(); // ==> 2
  • 58.
     function Pet() {}; Pet function Dog() {};  Dog.prototype = new Pet; Dog
  • 59.
    function Pet(name) { this.name= name; }; function Dog(name) { // super(name) Pet.call( this, name ); this.bark = function() {}; }; Dog.prototype = new Pet;
  • 60.
     // old: attachto "this“ function Dog(name) { this.bark = function(){ alert("Woof!") }; };  // new: attach to "prototype" function Dog(name) {}; Dog.prototype.bark = function(){ alert("Woof!") }; };
  • 61.
     Property values oninstance:  local, instance-specific values  Property values on prototype:  read-only default values attaching to the prototype saves memory, especially for large numbers of instances
  • 62.
     Affects all newinstances  Affects all existing instances  Allows modification of existing classes String.prototype.trim = function() { return this.replace(/^s+/, ""); }; alert(" Lassie".trim() );
  • 63.
    function Dog() {}; Dog.prototype.bark= function() { alert("Woof!") }; function Bulldog() {}; Bulldog.prototype = new Dog; Bulldog.prototype.bark = function() { // super.bark(); Dog.prototype.bark.call(this); alert("Grrrh!!") };
  • 64.
    function Pet() { if(this._id== Pet._id) { throw new Error("No Pets, please!"); } } Pet._id = "Pet"; Pet.prototype._id = "Pet"; var fiffy = new Pet; // Error (intended)
  • 65.
    But now ourcode to setup inheritance will fail: Dog.prototype = new Pet; // Error :-( Solution: Do not create an instance of the actual superclass just to setup inheritance, use a dummy: function Dummy() {}; Dummy.prototype = Pet.prototype; Dog.prototype = new Dummy;
  • 66.
    if (typeof very== "undefined") { very = {}; } if (typeof very.cute == "undefined") { very.cute = {}; } very.cute.Dog = function() {}; var fiffy = new very.cute.Dog;
  • 67.
    // The Lastof the Mohicans var chingachgook = { fight : function() { alert("Woah!"); } }; chingachgook.fight();
  • 68.
    function Mohican() { this.fight= function(){alert("Woah!")} }; Mohican.getInstance = function() { if (!this._instance) { this.instance = new this; } return this._instance; }; Mohican.getInstance().fight();
  • 70.
     Avoiding Conflicts withOther Libraries ($) <!-- Putting jQuery into no-conflict mode. --> <script src="prototype.js"></script> <script src="jquery.js"></script> <script> var $j = jQuery.noConflict(); // $j is now an alias to the jQuery function; creating the new alias is optional. $j(document).ready(function() { $j( "div" ).hide(); }); // The $ variable now has the prototype meaning, which is a shortcut for // document.getElementById(). mainDiv below is a DOM element, not a jQuery object. window.onload = function() { var mainDiv = $( "main" ); } </script>
  • 71.
     use multiple window.onloadevents with external scripts: window.onload = init; function addOnloadEvent(fnc){ if ( typeof window.addEventListener != "undefined" ) window.addEventListener( "load", fnc, false ); else if ( typeof window.attachEvent != "undefined" ) { window.attachEvent( "onload", fnc ); } else { if ( window.onload != null ) {var oldOnload = window.onload; window.onload = function ( e ) {oldOnload( e ); window[fnc]();}; } else window.onload = fnc; } } addOnloadEvent(myFunctionName);
  • 72.
     Feature-Detect Rather ThanBrowser-Detect if (document.getElementById) { var element = document.getElementById('MyId'); } else { alert('Your browser lacks the capabilities required to run this script!'); }  Use Square Bracket Notation MyObject.property MyObject."value"+I (Work) (not Work) formref.elements.name[] (not Work) MyObject["property"] (Work) MyObject["value"+i] (Work) formref.elements["name[]"] (Work)
  • 73.
     Use onclick InAnchors Instead Of javascript: Pseudo-Protocol <a href="/" onClick="return validate();">Home</a> function validate() { return prompt("Are you sure you want to exit this page?"); }  What Not To Do <a href="javascript:doSomething()">link</a> <a href="#" onClick="doSomething()">link</a> <a href="#" onClick="javascript:doSomething();">link</a> <a href="#" onClick="javascript:doSomething(); return false;">link</a>
  • 74.
     Use The Unary+ Operator To TypeConvert To Number function total() { var theform = document.forms["myform"]; var total = (+theform.elements["val1"].value) + (+theform.elements["val2"].value); alert(total); // This will alert 3 }  Don't Use HTML Comments In Script Blocks <script language="javascript"> <!-// code here //--> </script>
  • 75.
     Avoid Cluttering TheGlobal Namespace var MyLib = {}; // global Object cointainer MyLib.value = 1; MyLib.increment = function() { MyLib.value++; } MyLib.show = function() { alert(MyLib.value); } MyLib.value=6; MyLib.increment(); MyLib.show(); // alerts 7
  • 76.
        Model: organize the application'sdata layer. View: Templates to render HTML data in controllers and inject them into the DOM. Composed Views: divide the view into small blocks which can be reused or adapted to different scenarios. Controller : A controller is a list of functions that gets called back when the appropriate event happens.
  • 79.
     Extend Methods.  UIControls and Library.  Compatibility.  Performance.
  • 80.
     Jquery  The DojoToolkit  The Yahoo! User Interface Library  Prototype (and Script.aculo.us)  MooTools  ExtJS provides everything you need to build robust desktop and mobile web apps.
  • 83.
  • 85.
    Framework UI Bindings Composed Views Web Presentation Layer Plays Nicely WithOthers Backbone.js ✗ ✗ ✓ ✓ SproutCore 1.x ✓ ✓ ✗ ✗ Sammy.js ✗ ✗ ✓ ✓ Spine.js ✗ ✗ ✓ ✓ Cappuccino ✓ ✓ ✗ ✗ Knockout.js ✓ ✗ ✓ ✓ Javascript MVC ✗ ✓ ✓ ✓ Google Web Toolkit ✗ ✓ ✗ ✗ Google Closure ✗ ✓ ✓ ✗ Ember.js ✓ ✓ ✓ ✓ Angular.js ✓ ✗ ✓ ✓ Batman.js ✓ ✗ ✓ ✓
  • 86.
      Define local variables vardoc = document; elem = doc.getElementById(“objId”); Combine control conditions and control variable changes when using loops var x = 9; do { } while( x-- );
  • 87.
     Define arrays forHTML collection objects function array(items) { try { return Array.prototype.concat.call(items); } catch (ex) { var i = 0, len = items.length, result = Array(len); while (i < len) { result[i] = items[i];i++; } return result; } } var divs = array( document.getElementsByTagName('div') ); for (var i=0l i < divs.length; i++ ) { var div = document.createElement("div"); document.appendChild(div); }
  • 88.
     Appending DOM elementsall at once faster than adding them individually.  var div = document.getElementsByTagName("div"); var fragment = document.createDocumentFragment(); for ( var e = 0; e < elems.length; e++ ) { fragment.appendChild( elems[e] ); } for ( var i = 0; i < div.length; i++ ) { div[i].appendChild( fragment.cloneNode(true) ); }  Change CSS classes not styles
  • 89.
     Optimizing Events <ul id="menu"> <liid="home">Home</li> <li id="products">Products</li> <li id="portfolio">Portfolio</li> <li id="shop">Shop</li> </ul> var menuHandler = function(event) { event = event || window.event; var target = event.target || event.srcElement; if (target.id === 'home') {// go home} } document.getElementById('menu').addEventListener('cli ck',menuHandler);
  • 90.
     Avoid memory leaksand circular references in your closures //Classic case for circular references function foo(e,d) { $(e).on("click", function() { //Do something with d }); } //Break the cycle! function foo(e, d) { $(e).on("click", cbk(d)); } function cbk (d) { }     Avoid using eval Minimize file size Caching use external file Deferred execution
  • 91.
     Loading on demand <scriptsrc="lab.js"></script> <script> $LAB .script("jquery.js") .wait() .script("jquery.color.js") .script("jquery.otherplugin.js") .script("mylib.js") .wait() .script("unrelated1.js") .script("unrelated2.js"); </script>   Minimize file size (use minified files) Deferred execution
  • 92.
     Frame  Eval Html Encode: • escape • encodeURI • encodeURIComponent • html.replace(/</g,"&lt;").replace(/>/g,"&gt;")  Obfuscate using tool YUI Compressor. Will it protect javascript?
  • 93.
  • 94.
     Firebug (FF) MS Visual Web Developer (IE)  DragonFly (Opera)  Chrome  Drosera / Web Inspector (Safari)  Console: http://code.google.com/p/console-js/ http://patik.com/blog/complete-cross-browserconsole-log/
  • 95.
     Dojo Shrink Safe http://shrinksafe.dojotoolkit.org/ YUI http://refresh-sf.com/yui/  Dean Edwards Packer / Compress.js
  • 96.
     Yslow  Firebug Chrome's development tools
  • 97.
     In browser (easy)- JSUnit  Browser Control (comprehensive) – Selenium http://www.seleniumhq.org/  Simulated (fast) – Env.js http://www.envjs.com/
  • 98.
    – Understands JavaScript,hard to document complex features http://code.google.com/p/jsdoc-toolkit/  Natural Docs – Can document anything  MVCDoc – Can document anything, understands some JS.  JSDoc

Editor's Notes

  • #11 http://stackoverflow.com/questions/12823264/get-all-elements-in-the-body-tag-using-pure-javascript
  • #16 
  • #17 
  • #19 
  • #20 
  • #21 
  • #22 
  • #79 Jquery:http://jqueryui.com/demos/The Dojo Toolkit:http://demos.dojotoolkit.org/demos/The Yahoo! User Interface Library:Prototype (and Script.aculo.us):MooToolshttp://mootools.net/demos/Ext JS:http://www.sencha.com/products/extjs/examples/http://docs.sencha.com/extjs/4.2.1/extjs-build/examples/sandbox/sandbox.html
  • #82 Jquery:http://jqueryui.com/demos/The Dojo Toolkit:http://demos.dojotoolkit.org/demos/The Yahoo! User Interface Library:Prototype (and Script.aculo.us):MooToolshttp://mootools.net/demos/Ext JS:http://www.sencha.com/products/extjs/examples/http://docs.sencha.com/extjs/4.2.1/extjs-build/examples/sandbox/sandbox.html
  • #83 http://ocanvas.org/demos
  • #85 Demo:http://learn.knockoutjs.com/#/?tutorial=introhttp://knockoutjs.com/documentation/browser-support.html