SlideShare une entreprise Scribd logo
1  sur  87
Télécharger pour lire hors ligne
JavaScript Basics And
  DOM Manipulation
       Siarhei Barysiuk
s.barysiuk@sam-solutions.net
Our roadmap
Important tools to have
 “Mozilla Firefox is a free and open source web browser descended from the
  Mozilla Application Suite, managed by the Mozilla Corporation. Firefox had
  19.73% of the recorded usage share of web browsers as of August 2008,
   making it the second-most popular browser in current use worldwide.”
                              www.firefox.com



“Firebug integrates with Firefox to put a wealth of web development tools at your
  fingertips while you browse.You can edit, debug, and monitor CSS, HTML, and
                         JavaScript live in any web page.”
                            www.getfirebug.com



 “The Aptana Studio Community Edition provides a full-featured web development
   environment. The Community Edition represents the core pieces of the Aptana
  frameworks for editing, debugging, synchronization, and project management.”
                              www.aptana.com
JavaScript is more than form validation

                                www.go2web20.net
                               • A directory of web 2.0 applications
                               and services
                               • 2670 registered applications
JavaScript Primitive Types
JavaScript: Primitive types
There are five primitive data types in JavaScript:
    • number
    • string
    • boolean
    • null
    • undefined
Everything that is not a primitive is an object.
Numbers
JavaScript: Primitive types: Numbers
var n1 = 1;
out(typeof n1);              >> quot;numberquot;
				                         				
var n2 = 1.5;
out(typeof n2);              >> quot;numberquot;
				                         				

var n3 = 0100;
out(typeof n3);              >> quot;numberquot;
out (n3);                    >> 64
				                         				

var n4 = 0xFF;
out(typeof n4);              >> quot;numberquot;
out(n4);                     >> 255
JavaScript: Primitive types: Numbers

var n5 = 1e1;
out(typeof n5);              >> quot;numberquot;
out(n5);	 	 	
         	                   >> 10	 	 	 	
				                         				
var n6 = 2e+3;
out(typeof n6);              >> quot;numberquot;
out(n6);	 	 	
         	                   >> 2000	 	 	 	
				                         				

var n7 = 2e-3;
out(typeof n7);              >> quot;numberquot;
out(n7);                     >> 0.002
JavaScript: Primitive types: Numbers
var n8 = Infinity;
out(typeof n8);              >> quot;numberquot;
out(n8);                     >> Infinity
				                         				

var n9 = 1e309;
out(typeof n9);              >> quot;numberquot;
out(n9);                     >> Infinity
				                         				

var n10 = 6/0;
out(typeof n10);             >> quot;numberquot;
out(n10);                    >> Infinity
				                         				

var n11 = -1*Infinity;
out(typeof n11);             >> quot;numberquot;
out(n11);                    >> -Infinity
JavaScript: Primitive types: Numbers

var n12 = NaN;
out(typeof n12);                 >> quot;numberquot;
out(n12);                        >> NaN
				                             				

var n13 = 10 * quot;stringquot;;
out(typeof n13);                 >> quot;numberquot;
out(n13);                        >> NaN


var n14 = 1 + 1 + NaN;
out(typeof n14);                 >> quot;numberquot;
out(n14);                        >> NaN


   {                         }
       NaN - Not a Number.
Strings
JavaScript: Primitive types: Strings


var s1 = quot;some stringquot;;
out(typeof s1);                                >> quot;stringquot;
				                                           				

var s2 = 'a';
out(typeof s2);                                >> quot;stringquot;
				                                           				

var s3 = quot;10quot;;
out(typeof s3);                                >> quot;stringquot;




   {                                           }
       Any value placed between single or
       double quotes is considered a string.
JavaScript: Primitive types: String
var s41 = quot;onequot;;
var s42 = quot;twoquot;
var s43 = s41 + s42;
out(s43);                       >> quot;onetwoquot;
				                            				
var s51 = quot;10quot;;
out(typeof s51);                >> quot;stringquot;
var s52 = s51 * 5;
out(s52);                       >> 50
out(typeof s52);                >> quot;numberquot;
				                            				
var s6 = quot;1quot;;
out(typeof s6);                 >>   quot;stringquot;
out(++s6);                      >>   2
out(typeof s6);                 >>   quot;numberquot;
				                            	    			
var s7 = quot;some string 1quot;;
var s71 = s7 * 1;
out(typeof s7);                 >> quot;stringquot;
out(s71);                       >> NaN
out(typeof s71);                >> quot;numberquot;
Boolean
JavaScript: Primitive types: Boolean

var b1 = false;
out(typeof b1);               >> quot;booleanquot;
				                          				

var b2 = quot;some stringquot;;
var b21 = !b2;
var b22 = !!b2;
out(typeof b2);               >>   quot;stringquot;
out(b21);                     >>   false
out(typeof b21);              >>   quot;booleanquot;
out(b22);                     >>   true
out(typeof b22);              >>   quot;booleanquot;
JavaScript: Primitive types: Boolean
All values become true when converted to a boolean, with the exception
of the six falsy values:

    var   b31   =   quot;quot;;


                                 }
                                       if ( !b3* ) {
    var   b32   =   null;
                                       	 //executes this section	 	   	   	   	
    var   b33   =   false;                //...	 	 	
                                               	
    var   b34   =   NaN;               }
    var   b35   =   undefined;
    var   b36   =   0;
JavaScript: Primitive types: Boolean
Some interesting comparison operations:

                       !=                                   ==
                                                        Equality comparison:
            Non-equality comparison:
                                              Returns true when both operands are
         Returns true if the operands are
                                               equal. The operands are converted to
             not equal to each other.
                                              the same type before being compared.


                     !==                                  ===
      Non-equality comparison without type
                                               Equality and type comparison:
                   conversion:
                                              Returns true if both operands are
       Returns true if the operands are not
                                                 equal and of the same type.
        equal OR they are different types.
JavaScript: Primitive types: Boolean
Some interesting comparison operations:


var b4 = 2!=quot;2quot;;            >> false
var b41 = 2==quot;2quot;;           >> true
				                        				
var b42 = 2!==quot;2quot;;          >> true
var b43 = 2===quot;2quot;;          >> false
Null & Undefined
JavaScript: Primitive types: Null


var nl1 = null;
out(typeof nl1);               >> quot;objectquot;
out(nl1);                      >> null

var nl2 = 1 + null;
out(nl2);		 	 	                >> 1		 	 	

var nl3 = 1*null;
out(nl3);                      >> 0
JavaScript: Primitive types: Undefined

var u1 = {};
//try to access to nonexistent
//field of the object
out(typeof u1.nonexistent);      >> undefined
out(u1.nonexistent);             >> undefined
				                             				
var u2 = 1 + undefined;
out(u2);                         >> NaN
				                             				
var u3 = 1 * undefined;
out(u3);                         >> NaN
Arrays
JavaScript: Arrays
var a = [1,2,3];
                        >> quot;objectquot;
out(typeof a);
                        >> [1,2,3]
out(a);
                        >> 1
out(a[0]);
                        >> undefined
out(a[5]);
                        				
				
                        a[5] = quot;some stringquot;;
a[5] = quot;some stringquot;;
                        >> [1,2,3, undefined, undefined,quot;some
out(a);
                        stringquot;]
				
delete a[2];
                        >> [1,2, undefined, undefined,
out(a);
                        undefined, quot;some stringquot;]
				
                        				
delete a[5];
                        >> [1,2, undefined, undefined,
out(a);
                        undefined, undefined]
JavaScript: Arrays


var a2 = [[1,2,3],
[quot;string1quot;,quot;string2quot;,3]];
out(a2[0]);                 >> [1,2,3]
out(a2[1]);                 >> [quot;string1quot;,quot;string2quot;,3]
				                        				
var a3 = quot;onequot;;
out(typeof a3);             >>   quot;stringquot;
out(a3[0]);                 >>   quot;oquot;
out(typeof a3[0]);          >>   quot;stringquot;
out(a3[1]);                 >>   quot;nquot;
Questions?
Functions
JavaScript: Functions
The power of functions. Where most programming languages have a
special syntax for some object-oriented features, JavaScript just uses functions.

function sum(a,b) {
	 return a + b;
}

var r1 = sum(1,1);                       >> 2
JavaScript: Functions: Parameters
A function may not require any parameters, but if it does and you forget to pass
them, JavaScript will assign the value undefined to the ones you skipped.


function sum(a,b) {                     function sum(a,b) {
	 return a + b;                         	 return a + b;
}                                       }

var r2 = sum(1);                        var r3 = sum(1,2,3,4,5);


     r2 >> NaN                                  r3 >> 3




    {                         }
        1 + undefined = NaN
JavaScript: Functions: Parameters
            is array of parameters which function accepts.
arguments


function sumAll() {
	 var result = 0;
	 for(var i=0,length=arguments.length;i<length;i++){
	 	 result+=arguments[i];
	}
	 return result;
}

var r4 = sum(1,2,3,4,5,6,7);

    r4 >> 28
JavaScript: Functions: Scope
Variables in JavaScript are not defined in a block scope, but in a function scope.

This means that
• if a variable is defined inside a function, it's not visible outside of the function.
• if a variable defined inside an if or a for code block is visible outside the code
block.
function func() {
	 var a = quot;localquot;;
	 if(true) {
	 	 out(a);                                >> quot;localquot;
	 	 var a2 = quot;local-ifquot;;
	 	 out(a2);                               >> quot;local-ifquot;
	}
	 out(a);                                  >> quot;localquot;
	 out(a2);                                 >> quot;local-ifquot;
}
JavaScript: Functions: Function literal notation
Functions are like any other variable.




var func3 = function(a,b) {
                                         typeof func3 >> quot;functionquot;
  	 	 return a*b;
                                         typeof f3 >> quot;functionquot;
	 	 };
                                         func3(2,2) >> 4	 	
                                         f3(3,3) >> 9		
var f3 = func3;
JavaScript: Functions: Built-in constructor


var func6 = new Function(quot;a,bquot;,quot;return a+b;quot;);
func6(2,2) >> 4




   {                                                                                    }
       Do not use the Function() constructor. As with eval() and setTimeout(),
       always try to stay away from cases where you pass JavaScript code as a string.
JavaScript: Functions: Anonymous Functions
•You can pass an anonymous function as a parameter to another function.
•You can define an anonymous function and execute it right away.
function execute(func) {
	 out(func());                                	 >> quot;hello, i'm anonymous function!quot;
}

execute(function() {
   return quot;hello, i'm anonymous function!quot;;
});




(function(a,b) {
	 out(a-b);                                     >> 2
})(5,3);
JavaScript: Functions: Callback Functions

function info(){
	 return quot;this is info function.quot;;
}

function execute(func) {
	 out(func());                                 anonymous callback
                                                    function
}


execute(function() {
    return quot;hello, i'm anonymous function!quot;;
});                                             callback function

execute(info);
JavaScript: Functions: Inner functions
•Keep the global namespace clean
•Privacy

                                                              define function
function funcTop() {

	 	 	 	 var a = function() {
	 	 	 	 	 out(quot;innerFunction: do some work...quot;);
				}

	 	 	 	 out(quot;funcTop: do some work...quot;);
	 	 	 	 a();
			}

                                                   call function
JavaScript: Functions: Scope

 var r5 = quot;globalquot;;            var r5 = quot;globalquot;;

 function func1() {            function func1() {
 	 out(r5);                    	 out(r5);
 	 var r5 = quot;localquot;;           }
 	 out(r5);
 }                             func1();

 func1();


                                 r5 >> quot;globalquot;
  r5 >> undefined
   r5 >> quot;localquot;
JavaScript: Functions: Lexical scope
In JavaScript, functions have lexical scope. This means that functions create their
environment (scope) when they are defined, not when they are executed.

 function func4() {                           function func41() {
 	 	 var v = 1;                                   var v = 1;
 	 	 return func5();
 };                                                	 return (function() {
                                                     	 	 return v;
 function func5() {                                	 })();	
    	 return v;                               };
 };
                                              out(func41());
 out(func4());

 >> ReferenceError: v is not defined          >> 1
JavaScript: Functions: Lexical scope
                                       var a;
                                       //..
                     Global            function F() {
                                       	 var b;
            F
                                       	 //..
        b                              	 function N() {
                              a
                                       	 	 var c;
                Nc
                                       	 	 //..
                                       	}
                                       }
JavaScript: Functions: Lexical scope
                                       var a;
                                       var N;
                   Global              //..
                                       function F() {
            F                          	 var b;
        b                                //..
                            a
                                         N = function () {
                                       	 	 	 	 	 var c;
                     Nc                	 	 	 	 	 //..
                                       			}
                                       }
Questions?
Objects
JavaScript: Objects
JavaScript uses
•arrays to represent indexed arrays
•objects to represent associative arrays (hashes)
var obj = {
                                 typeof obj >> object
	 prop:1,
                                 obj.prop >> obj[quot;unusual-propquot;] >> quot;valuequot;
	 prop2:quot;stringquot;,
                                 obj['WTF?$#!@$'].a >> quot;a-valquot;
	 quot;unusual-propquot;:quot;valuequot;,
                                 obj.array >> [1,2,3]
	 'WTF?$#!@$':{
                                 obj[quot;arrayquot;] >> [1,2,3]
	 	 a:quot;a-valquot;
	 },
	 array: [1,2,3]	
};
JavaScript: Objects : Defining a new property


var obj = {
	 prop:1,
                               obj.prop3 >> undefined
	 prop2:quot;stringquot;,
                               obj.prop3 = quot;value3quot;;
	 quot;unusual-propquot;:quot;valuequot;,
                               obj.prop3 >> quot;value3quot;
	 'WTF?$#!@$':{
	 	 a:quot;a-valquot;
	 },
	 array: [1,2,3]	
};
JavaScript: Objects : Passing
Passing objects by reference.

   var obj1 = {                 //..
   	 a:quot;val-aquot;                  var obj3 = {
   };                           	 a:quot;val-aquot;
                                };
   var obj2 = obj1;
   				                         obj1===obj2 >> true
   obj1.a >> quot;val-aquot;            obj1===obj3 >> false
   obj2.a >> quot;val-aquot;
   				
   obj2.a = quot;val-a2quot;;
   				
   obj1.a >> quot;val-a2quot;
   obj2.a >> quot;val-a2quot;
JavaScript: Objects: Functions

var dog = {
                                 dog.name >> quot;Bobikquot;
	 name: quot;Bobikquot;,
                                 dog.talk() >> quot;Woof, woof!quot;
	 talk: function() {
                                 dog.sayName() >> quot;Bobikquot;
	 	 return quot;Woof, woof!quot;;
	 },
	 sayName: function() {
	 	 return this.name;
	}
};
JavaScript: Objects: Constructor

function Cat(/*String*/ name) {
	 this.name = name;
	 this.talk = function() {
	 	 return quot;I'm quot;+this.name+quot;. Mrrr, miaow!quot;;
	}
}

var cat = new Cat(quot;Barsikquot;);

typeof cat >> object
cat.name >> quot;Barsikquot;
cat.talk() >> quot;I’m Barsik. Mrrr, miaow!quot;
JavaScript: Objects: Constructor
function Cat(/*String*/ name) {              this refers to the global
	 this.name = name;                               object window
	 this.talk = function() {
	 	 //...
	}
}                          call without
                                 new
var cat2 = Cat(quot;Barsikquot;);



typeof cat2 >> undefined
cat2.name >> TypeError: cat2 has no properties

window.name >> quot;Barsikquot;
JavaScript: Objects: Constructor
When an object is created, a special property is assigned to it behind
the scenes — the constructor property.

var cat = new Cat(quot;Barsikquot;);

var constr = cat.constructor;
var cat3 = cat.constructor(quot;Murzikquot;);
				

constr >> function Cat(name) { .... }
cat3.talk() >> quot;I’m Murzik. Mrrr, miaow!quot;
JavaScript: Objects: call and apply
Two useful methods of the function objects are call() and apply().

They allow your objects to borrow methods from other objects and
invoke them as their own.


var cat = new Cat(quot;Barsikquot;);
//..
var cat4 = {name:quot;Chernyshquot;};

cat.talk.call(cat4/**, param1, param2, ... **/) >> quot;I’m Chernysh. Mrrr, miaow!quot;
cat.talk.apply(cat4/**, [param1, param2, ...] **/) >> quot;I’m Chernysh. Mrrr, miaow!quot;
JavaScript: Objects: instanceof
             operator tests if an object was created with specific constructor
instanceof
function.

var cat = new Cat(quot;Barsikquot;);
var o = {};

cat instanceof Cat >> true
cat instanceof Object >> true

o instanceof Object >> true
o instanceof Cat >> false
Questions?
Prototype
JavaScript: Prototype: Intro


  • not be confusing things, it’s not prototype.js library
  • JavaScript has prototype-based object model
JavaScript: Prototype: prototype property

function Cat(/*String*/ name) {
   this.name = name;
	 this.talk = function() {
	 	 return quot;I'm quot;+this.name+quot;. Mrrr, miaow!quot;;
	}
};
                                                  the way how enumerate all
                                                    properties in an object
Cat.prototype >> {} (object)
				
for(var i in Cat.prototype) {
	 i+quot;:quot;+Cat.prototype[i] >> ${propName}:${propValue}
}
JavaScript: Prototype: Adding properties
Adding methods and properties to the prototype property of the constructor
function is another way to add functionality to the objects this constructor
produces.

var cat = new Cat(quot;Barsikquot;);
Cat.prototype.animal = quot;catquot;;

Cat.prototype >> {animal: quot;catquot;}
cat.animal >> quot;catquot;

Cat.prototype.seeADog = function() {
	 return quot;I'm quot;+this.name+quot;. Sshhhhhhh!quot;;
}
				
cat.seeADog() >> quot;I'm Barsik. Sshhhhhhh!quot;;
JavaScript: Prototype: Adding properties
The same result as in the previous example ...


 var cat = new Cat(quot;Barsikquot;);                    Overriding the prototype
 Cat.prototype.animal = quot;catquot;;                         completely

 Cat.prototype = {
 	 animal: quot;catquot;,
 	 seeADog : function() {
 	 	 return quot;I'm quot;+this.name+quot;. Sshhhhhhh!quot;;
 	}
 }

 cat.animal >> quot;catquot;
 cat.seeADog() >> quot;I'm Barsik. Sshhhhhhh!quot;;
JavaScript: Prototype: Changing prototype
var cat = new Cat(quot;Barsikquot;);
var cat2 = new Cat(quot;Murzikquot;);

Cat.prototype.animal = quot;catquot;;
                                       Changing the prototype for all
                                              Cat instances
cat.animal >> quot;catquot;
cat2.animal >> quot;catquot;

Cat.prototype.animal = quot;dogquot;;

cat.animal >> quot;dogquot;
cat2.animal >> quot;dogquot;
JavaScript: Prototype: Own props vs. prototype ones

function Gadget(/*String*/ name) {
	 this.name = name;
}

var iphone = new Gadget(quot;iPhonequot;);

Gadget.prototype.name = quot;nonequot;;

iphone.name >> quot;iPhonequot;
delete iphone.name;
iphone.name >> quot;nonequot;
JavaScript: Prototype: Extending built-in objects
Yeah, it’s possible...

String.prototype.getSecondLetter = function() {
	 return this[1];
}
				
var str = quot;hello!quot;;
str.getSecondLetter() >> quot;equot;

... but be careful.
Inheritance
JavaScript: Inheritance: Prototype Chaining Example
function Shape() {
	 this.name = quot;Shapequot;;
	 this.getName = function() {
	 	 return this.name;
	}
};
				
function TwoDShape() {
	 this.name = quot;2DShapequot;;
};
				
function Triangle(/*Number*/ side, /*Number*/
height) {
	 this.side = side;
	 this.height = height;
	 this.name = quot;Trianglequot;;
	 this.getArea = function() {
	 	 return this.side * this.height / 2;
	}
}
JavaScript: Inheritance: Prototype Chaining Example
TwoDShape.prototype = new Shape();
Triangle.prototype = new TwoDShape();
                                               	    	   	   	
				
TwoDShape.prototype.constructor = TwoDShape;
Triangle.prototype.constructor = Triangle;

var t = new Triangle(10,4);
                                               >> 20
out(t.getArea());
                                               >> Triangle
out(t.getName());

                                               >> function Triangle(side,height){...}
out(t.constructor);

out(t   instanceof   Triangle);                >>   true
out(t   instanceof   TwoDShape);               >>   true
out(t   instanceof   Shape);                   >>   true
out(t   instanceof   String);                  >>   false

out(Triangle.prototype.isPrototypeOf(t));      >>   true
out(TwoDShape.prototype.isPrototypeOf(t));     >>   true
out(Shape.prototype.isPrototypeOf(t));         >>   true
out(String.prototype.isPrototypeOf(t));        >>   false

var shape = new Shape();
out(shape.getName());                          >> Shape
JavaScript: Inheritance: Shared Properties
Move shared properties to prototype.

function Obj() {                          function Obj() {};
                                     ==
	 this.text = quot;Hello this world!quot;;        Obj.prototype.text = quot;Hello this world!quot;;
};



But how about memory usage?
JavaScript: Inheritance: Some profiling results

      Activity Monitor             v. 3.0.1 Mac OS
                                         prototype property
                                         this. property
JavaScript: Inheritance: Inheriting the prototype only
function Shape() {}
Shape.prototype.name = quot;Shapequot;;
Shape.prototype.getName = function() {
	 return this.name;
};
					
function TwoDShape() {}
TwoDShape.prototype = Shape.prototype;
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.prototype.name = quot;2DShapequot;;
				
				
function Triangle(/*Number*/ side, /*Number*/ height) {
	 this.side = side;
	 this.height = height;
}

Triangle.prototype = TwoDShape.prototype;
Triangle.prototype.constructor = Triangle;

Triangle.prototype.name = quot;Trianglequot;;
Triangle.prototype.getArea = function() {
	 return this.side * this.height / 2;
}
JavaScript: Inheritance: Inheriting the prototype only

var t = new Triangle(10,4);
                                             >> 20
out(t.getArea());
                                             >> Triangle
out(t.getName());

                                             >> function Triangle(side,height){...}
out(t.constructor);

out(t   instanceof   Triangle);              >>   true
out(t   instanceof   TwoDShape);             >>   true
out(t   instanceof   Shape);                 >>   true
out(t   instanceof   String);                >>   false

out(Triangle.prototype.isPrototypeOf(t));    >>   true
out(TwoDShape.prototype.isPrototypeOf(t));   >>   true
out(Shape.prototype.isPrototypeOf(t));       >>   true
out(String.prototype.isPrototypeOf(t));      >>   false

var shape = new Shape();
out(shape.getName());                        >> Triangle
Questions?
Even more...
JavaScript: General: Even more...

• Math - mathematical constants and functions.
• Date - working with dates.
• RegExp - regular expressions.
  See more info on


                   www.developer.mozilla.org
JavaScript: General: Exception handling

 try {
 	 iDontExist();
 }
 catch(e){
 	 //process error here
   out(e);                >> ReferenceError: iDontExist is not defined
 }
 finally {
 	 //do some work here
 }
JavaScript: General: Exception handling

 • EvalError
 • RangeError
 • ReferenceError
 • SyntaxError
 • TypeError
 • URIError
 • Your own with new Error([message[, fileName[, lineNumber]]])
Questions?
Document Object Model
DOM: Introduction
The Document Object Model, a language-neutral set of
interfaces.

The Document Object Model is an API for HTML and XML
documents. It provides a structural representation of the
document, enabling you to modify its content and visual
presentation. Essentially, it connects web pages to scripts
or programming languages.
DOM: Chair Construction Analogy




          Model                   API
DOM: HTML document
<!DOCTYPE HTML PUBLIC quot;-//W3C//DTD HTML 4.01//ENquot;
                      quot;http://www.w3.org/TR/html4/strict.dtdquot;>
<html>
	 <head>
	 	 <meta http-equiv=quot;Content-Typequot;
           content=quot;text/html; charset=UTF-8quot; />
	 	 <title>ToDo list</title>
	 </head>
	 <body>
	 	 <div>What I need to do.</div>
	 	 <p title=quot;ToDo listquot;>My list:</p>
	 	 <ul>
	 	 	 <li>Finish presentation</li>
	 	 	 <li>Clean up my home.</li>
	 	 	 <li>Buy a bottle of milk.
              (May be beer will be better?;)
        </li>
	 	 </ul>
	 </body>
</html>
DOM: Finding elements
<input type=quot;textquot; id=quot;messagequot; value=quot;Messages goes here...quot;/>

...

var msgInput = document.getElementById(quot;messagequot;);

                                                           element or null

 <ul id=quot;listquot;>
 	 <li>Item 1</li>
 	 <li>Item 2</li>
                                                        array of element or an
 	 <li>Item 3</li>
                                                             empty array
 </ul>

 ...

 var items = document.getElementsByTagName(quot;liquot;);
DOM: Elements

 <p title=quot;ToDo listquot;>My tasks</p>



 Node types:

 an HTML element - 1
 an attribute - 2
 a text node - 3
DOM: Element attributes
 • nodeName
 • nodeValue
 • nodeType
 • parentNode
 • childNodes
 • firstChild
 • lastChild
 • previousSibling
 • nextSibling
 • attributes
 • ownerDocument
DOM: Manipulating the DOM
var item = document.createElement(quot;liquot;);
var text = document.createTextNode(message);
item.appendChild(text);

parent.appendChild(item);


parent.insertBefore(someNode, item);



parent.innerHTML = parent.innerHTML + (quot;<li>quot;+message+quot;</li>quot;);


parent.removeChild(item);
DOM: Event Handlers

var addBtn = document.getElementById(quot;addBtnquot;);
var list = document.getElementById(quot;listquot;);
if(addBtn) {
	 addBtn.onclick = function(event) {
             console.log(event);
             var value = msgInput.value;
	 	 	 	 	 if(value) {
	 	 	 	 	 	 createListEntry(list,value);
					}
	 	 	 	 	 else {
	 	 	 	 	 	 alert(quot;Message is empty!quot;);
					}
				}
}
DOM: Events: Capturing and Bubbling
     var addBtn =
     document.getElementById(quot;addBtnquot;);

     //...

     addBtn.addEventListener('click',
     function(){
     	 //code goes here
     },false);

     addBtn.attachEvent('click', function(){
     	 	 	 	 	 //code goes here
     });
DOM: Events: Capturing and Bubbling
DOM: Let’s see an example
                            ToDos application

                            • adding tasks
                            • deleting tasks
                            • reordering tasks
                            • no backend support

                            Very early alpha ;)
Questions?

Contenu connexe

Tendances

Tendances (20)

Unit 2 dhtml
Unit 2 dhtmlUnit 2 dhtml
Unit 2 dhtml
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
Presentation of bootstrap
Presentation of bootstrapPresentation of bootstrap
Presentation of bootstrap
 
Introduction to CSS Grid Layout
Introduction to CSS Grid LayoutIntroduction to CSS Grid Layout
Introduction to CSS Grid Layout
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Intro to HTML and CSS basics
Intro to HTML and CSS basicsIntro to HTML and CSS basics
Intro to HTML and CSS basics
 
CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations CSS Transitions, Transforms, Animations
CSS Transitions, Transforms, Animations
 
Bootstrap 5 ppt
Bootstrap 5 pptBootstrap 5 ppt
Bootstrap 5 ppt
 
Bootstrap PPT by Mukesh
Bootstrap PPT by MukeshBootstrap PPT by Mukesh
Bootstrap PPT by Mukesh
 
Css Basics
Css BasicsCss Basics
Css Basics
 
cascading style sheet ppt
cascading style sheet pptcascading style sheet ppt
cascading style sheet ppt
 
Basic html
Basic htmlBasic html
Basic html
 
Css ppt
Css pptCss ppt
Css ppt
 
Java script
Java scriptJava script
Java script
 
Flexbox
FlexboxFlexbox
Flexbox
 
Css Display Property
Css Display PropertyCss Display Property
Css Display Property
 
Html5 and-css3-overview
Html5 and-css3-overviewHtml5 and-css3-overview
Html5 and-css3-overview
 
Flexbox and Grid Layout
Flexbox and Grid LayoutFlexbox and Grid Layout
Flexbox and Grid Layout
 
Html 5
Html 5Html 5
Html 5
 
Javascript dom event
Javascript dom eventJavascript dom event
Javascript dom event
 

En vedette

En vedette (12)

JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Javascript
JavascriptJavascript
Javascript
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Java script ppt
Java script pptJava script ppt
Java script ppt
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Javascript
JavascriptJavascript
Javascript
 
Js ppt
Js pptJs ppt
Js ppt
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 

Similaire à JavaScript Basics And DOM Manipulation

development, ruby, conferences, frameworks, ruby on rails, confreaks, actsasc...
development, ruby, conferences, frameworks, ruby on rails, confreaks, actsasc...development, ruby, conferences, frameworks, ruby on rails, confreaks, actsasc...
development, ruby, conferences, frameworks, ruby on rails, confreaks, actsasc...
ActsAsCon
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrong
Julien Wetterwald
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
Adhoura Academy
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
Adam Crabtree
 

Similaire à JavaScript Basics And DOM Manipulation (20)

Relaxing With CouchDB
Relaxing With CouchDBRelaxing With CouchDB
Relaxing With CouchDB
 
development, ruby, conferences, frameworks, ruby on rails, confreaks, actsasc...
development, ruby, conferences, frameworks, ruby on rails, confreaks, actsasc...development, ruby, conferences, frameworks, ruby on rails, confreaks, actsasc...
development, ruby, conferences, frameworks, ruby on rails, confreaks, actsasc...
 
Javascript
JavascriptJavascript
Javascript
 
Functional Concepts for OOP Developers
Functional Concepts for OOP DevelopersFunctional Concepts for OOP Developers
Functional Concepts for OOP Developers
 
JavaScript Beginner Tutorial | WeiYuan
JavaScript Beginner Tutorial | WeiYuanJavaScript Beginner Tutorial | WeiYuan
JavaScript Beginner Tutorial | WeiYuan
 
Javascript Basic
Javascript BasicJavascript Basic
Javascript Basic
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScript
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrong
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
 
Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
JSUG - Scala Lightning Talk by Michael Greifeneder
JSUG - Scala Lightning Talk by Michael GreifenederJSUG - Scala Lightning Talk by Michael Greifeneder
JSUG - Scala Lightning Talk by Michael Greifeneder
 
Gtg12
Gtg12Gtg12
Gtg12
 
Impacta - Show Day de Rails
Impacta - Show Day de RailsImpacta - Show Day de Rails
Impacta - Show Day de Rails
 
Scti 2011 minicurso jquery
Scti 2011 minicurso jqueryScti 2011 minicurso jquery
Scti 2011 minicurso jquery
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
 
Jquery 1
Jquery 1Jquery 1
Jquery 1
 
Scala en
Scala enScala en
Scala en
 

Plus de Siarhei Barysiuk (6)

Pure css skinning with menu box and menu
Pure css skinning with menu box and menuPure css skinning with menu box and menu
Pure css skinning with menu box and menu
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application Security
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
JavaScript Libraries Overview
JavaScript Libraries OverviewJavaScript Libraries Overview
JavaScript Libraries Overview
 
AJAX Transport Layer
AJAX Transport LayerAJAX Transport Layer
AJAX Transport Layer
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

JavaScript Basics And DOM Manipulation

  • 1.
  • 2. JavaScript Basics And DOM Manipulation Siarhei Barysiuk s.barysiuk@sam-solutions.net
  • 4. Important tools to have “Mozilla Firefox is a free and open source web browser descended from the Mozilla Application Suite, managed by the Mozilla Corporation. Firefox had 19.73% of the recorded usage share of web browsers as of August 2008, making it the second-most popular browser in current use worldwide.” www.firefox.com “Firebug integrates with Firefox to put a wealth of web development tools at your fingertips while you browse.You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.” www.getfirebug.com “The Aptana Studio Community Edition provides a full-featured web development environment. The Community Edition represents the core pieces of the Aptana frameworks for editing, debugging, synchronization, and project management.” www.aptana.com
  • 5. JavaScript is more than form validation www.go2web20.net • A directory of web 2.0 applications and services • 2670 registered applications
  • 7. JavaScript: Primitive types There are five primitive data types in JavaScript: • number • string • boolean • null • undefined Everything that is not a primitive is an object.
  • 9. JavaScript: Primitive types: Numbers var n1 = 1; out(typeof n1); >> quot;numberquot; var n2 = 1.5; out(typeof n2); >> quot;numberquot; var n3 = 0100; out(typeof n3); >> quot;numberquot; out (n3); >> 64 var n4 = 0xFF; out(typeof n4); >> quot;numberquot; out(n4); >> 255
  • 10. JavaScript: Primitive types: Numbers var n5 = 1e1; out(typeof n5); >> quot;numberquot; out(n5); >> 10 var n6 = 2e+3; out(typeof n6); >> quot;numberquot; out(n6); >> 2000 var n7 = 2e-3; out(typeof n7); >> quot;numberquot; out(n7); >> 0.002
  • 11. JavaScript: Primitive types: Numbers var n8 = Infinity; out(typeof n8); >> quot;numberquot; out(n8); >> Infinity var n9 = 1e309; out(typeof n9); >> quot;numberquot; out(n9); >> Infinity var n10 = 6/0; out(typeof n10); >> quot;numberquot; out(n10); >> Infinity var n11 = -1*Infinity; out(typeof n11); >> quot;numberquot; out(n11); >> -Infinity
  • 12. JavaScript: Primitive types: Numbers var n12 = NaN; out(typeof n12); >> quot;numberquot; out(n12); >> NaN var n13 = 10 * quot;stringquot;; out(typeof n13); >> quot;numberquot; out(n13); >> NaN var n14 = 1 + 1 + NaN; out(typeof n14); >> quot;numberquot; out(n14); >> NaN { } NaN - Not a Number.
  • 14. JavaScript: Primitive types: Strings var s1 = quot;some stringquot;; out(typeof s1); >> quot;stringquot; var s2 = 'a'; out(typeof s2); >> quot;stringquot; var s3 = quot;10quot;; out(typeof s3); >> quot;stringquot; { } Any value placed between single or double quotes is considered a string.
  • 15. JavaScript: Primitive types: String var s41 = quot;onequot;; var s42 = quot;twoquot; var s43 = s41 + s42; out(s43); >> quot;onetwoquot; var s51 = quot;10quot;; out(typeof s51); >> quot;stringquot; var s52 = s51 * 5; out(s52); >> 50 out(typeof s52); >> quot;numberquot; var s6 = quot;1quot;; out(typeof s6); >> quot;stringquot; out(++s6); >> 2 out(typeof s6); >> quot;numberquot; var s7 = quot;some string 1quot;; var s71 = s7 * 1; out(typeof s7); >> quot;stringquot; out(s71); >> NaN out(typeof s71); >> quot;numberquot;
  • 17. JavaScript: Primitive types: Boolean var b1 = false; out(typeof b1); >> quot;booleanquot; var b2 = quot;some stringquot;; var b21 = !b2; var b22 = !!b2; out(typeof b2); >> quot;stringquot; out(b21); >> false out(typeof b21); >> quot;booleanquot; out(b22); >> true out(typeof b22); >> quot;booleanquot;
  • 18. JavaScript: Primitive types: Boolean All values become true when converted to a boolean, with the exception of the six falsy values: var b31 = quot;quot;; } if ( !b3* ) { var b32 = null; //executes this section var b33 = false; //... var b34 = NaN; } var b35 = undefined; var b36 = 0;
  • 19. JavaScript: Primitive types: Boolean Some interesting comparison operations: != == Equality comparison: Non-equality comparison: Returns true when both operands are Returns true if the operands are equal. The operands are converted to not equal to each other. the same type before being compared. !== === Non-equality comparison without type Equality and type comparison: conversion: Returns true if both operands are Returns true if the operands are not equal and of the same type. equal OR they are different types.
  • 20. JavaScript: Primitive types: Boolean Some interesting comparison operations: var b4 = 2!=quot;2quot;; >> false var b41 = 2==quot;2quot;; >> true var b42 = 2!==quot;2quot;; >> true var b43 = 2===quot;2quot;; >> false
  • 22. JavaScript: Primitive types: Null var nl1 = null; out(typeof nl1); >> quot;objectquot; out(nl1); >> null var nl2 = 1 + null; out(nl2); >> 1 var nl3 = 1*null; out(nl3); >> 0
  • 23. JavaScript: Primitive types: Undefined var u1 = {}; //try to access to nonexistent //field of the object out(typeof u1.nonexistent); >> undefined out(u1.nonexistent); >> undefined var u2 = 1 + undefined; out(u2); >> NaN var u3 = 1 * undefined; out(u3); >> NaN
  • 25. JavaScript: Arrays var a = [1,2,3]; >> quot;objectquot; out(typeof a); >> [1,2,3] out(a); >> 1 out(a[0]); >> undefined out(a[5]); a[5] = quot;some stringquot;; a[5] = quot;some stringquot;; >> [1,2,3, undefined, undefined,quot;some out(a); stringquot;] delete a[2]; >> [1,2, undefined, undefined, out(a); undefined, quot;some stringquot;] delete a[5]; >> [1,2, undefined, undefined, out(a); undefined, undefined]
  • 26. JavaScript: Arrays var a2 = [[1,2,3], [quot;string1quot;,quot;string2quot;,3]]; out(a2[0]); >> [1,2,3] out(a2[1]); >> [quot;string1quot;,quot;string2quot;,3] var a3 = quot;onequot;; out(typeof a3); >> quot;stringquot; out(a3[0]); >> quot;oquot; out(typeof a3[0]); >> quot;stringquot; out(a3[1]); >> quot;nquot;
  • 29. JavaScript: Functions The power of functions. Where most programming languages have a special syntax for some object-oriented features, JavaScript just uses functions. function sum(a,b) { return a + b; } var r1 = sum(1,1); >> 2
  • 30. JavaScript: Functions: Parameters A function may not require any parameters, but if it does and you forget to pass them, JavaScript will assign the value undefined to the ones you skipped. function sum(a,b) { function sum(a,b) { return a + b; return a + b; } } var r2 = sum(1); var r3 = sum(1,2,3,4,5); r2 >> NaN r3 >> 3 { } 1 + undefined = NaN
  • 31. JavaScript: Functions: Parameters is array of parameters which function accepts. arguments function sumAll() { var result = 0; for(var i=0,length=arguments.length;i<length;i++){ result+=arguments[i]; } return result; } var r4 = sum(1,2,3,4,5,6,7); r4 >> 28
  • 32. JavaScript: Functions: Scope Variables in JavaScript are not defined in a block scope, but in a function scope. This means that • if a variable is defined inside a function, it's not visible outside of the function. • if a variable defined inside an if or a for code block is visible outside the code block. function func() { var a = quot;localquot;; if(true) { out(a); >> quot;localquot; var a2 = quot;local-ifquot;; out(a2); >> quot;local-ifquot; } out(a); >> quot;localquot; out(a2); >> quot;local-ifquot; }
  • 33. JavaScript: Functions: Function literal notation Functions are like any other variable. var func3 = function(a,b) { typeof func3 >> quot;functionquot; return a*b; typeof f3 >> quot;functionquot; }; func3(2,2) >> 4 f3(3,3) >> 9 var f3 = func3;
  • 34. JavaScript: Functions: Built-in constructor var func6 = new Function(quot;a,bquot;,quot;return a+b;quot;); func6(2,2) >> 4 { } Do not use the Function() constructor. As with eval() and setTimeout(), always try to stay away from cases where you pass JavaScript code as a string.
  • 35. JavaScript: Functions: Anonymous Functions •You can pass an anonymous function as a parameter to another function. •You can define an anonymous function and execute it right away. function execute(func) { out(func()); >> quot;hello, i'm anonymous function!quot; } execute(function() { return quot;hello, i'm anonymous function!quot;; }); (function(a,b) { out(a-b); >> 2 })(5,3);
  • 36. JavaScript: Functions: Callback Functions function info(){ return quot;this is info function.quot;; } function execute(func) { out(func()); anonymous callback function } execute(function() { return quot;hello, i'm anonymous function!quot;; }); callback function execute(info);
  • 37. JavaScript: Functions: Inner functions •Keep the global namespace clean •Privacy define function function funcTop() { var a = function() { out(quot;innerFunction: do some work...quot;); } out(quot;funcTop: do some work...quot;); a(); } call function
  • 38. JavaScript: Functions: Scope var r5 = quot;globalquot;; var r5 = quot;globalquot;; function func1() { function func1() { out(r5); out(r5); var r5 = quot;localquot;; } out(r5); } func1(); func1(); r5 >> quot;globalquot; r5 >> undefined r5 >> quot;localquot;
  • 39. JavaScript: Functions: Lexical scope In JavaScript, functions have lexical scope. This means that functions create their environment (scope) when they are defined, not when they are executed. function func4() { function func41() { var v = 1; var v = 1; return func5(); }; return (function() { return v; function func5() { })(); return v; }; }; out(func41()); out(func4()); >> ReferenceError: v is not defined >> 1
  • 40. JavaScript: Functions: Lexical scope var a; //.. Global function F() { var b; F //.. b function N() { a var c; Nc //.. } }
  • 41. JavaScript: Functions: Lexical scope var a; var N; Global //.. function F() { F var b; b //.. a N = function () { var c; Nc //.. } }
  • 44. JavaScript: Objects JavaScript uses •arrays to represent indexed arrays •objects to represent associative arrays (hashes) var obj = { typeof obj >> object prop:1, obj.prop >> obj[quot;unusual-propquot;] >> quot;valuequot; prop2:quot;stringquot;, obj['WTF?$#!@$'].a >> quot;a-valquot; quot;unusual-propquot;:quot;valuequot;, obj.array >> [1,2,3] 'WTF?$#!@$':{ obj[quot;arrayquot;] >> [1,2,3] a:quot;a-valquot; }, array: [1,2,3] };
  • 45. JavaScript: Objects : Defining a new property var obj = { prop:1, obj.prop3 >> undefined prop2:quot;stringquot;, obj.prop3 = quot;value3quot;; quot;unusual-propquot;:quot;valuequot;, obj.prop3 >> quot;value3quot; 'WTF?$#!@$':{ a:quot;a-valquot; }, array: [1,2,3] };
  • 46. JavaScript: Objects : Passing Passing objects by reference. var obj1 = { //.. a:quot;val-aquot; var obj3 = { }; a:quot;val-aquot; }; var obj2 = obj1; obj1===obj2 >> true obj1.a >> quot;val-aquot; obj1===obj3 >> false obj2.a >> quot;val-aquot; obj2.a = quot;val-a2quot;; obj1.a >> quot;val-a2quot; obj2.a >> quot;val-a2quot;
  • 47. JavaScript: Objects: Functions var dog = { dog.name >> quot;Bobikquot; name: quot;Bobikquot;, dog.talk() >> quot;Woof, woof!quot; talk: function() { dog.sayName() >> quot;Bobikquot; return quot;Woof, woof!quot;; }, sayName: function() { return this.name; } };
  • 48. JavaScript: Objects: Constructor function Cat(/*String*/ name) { this.name = name; this.talk = function() { return quot;I'm quot;+this.name+quot;. Mrrr, miaow!quot;; } } var cat = new Cat(quot;Barsikquot;); typeof cat >> object cat.name >> quot;Barsikquot; cat.talk() >> quot;I’m Barsik. Mrrr, miaow!quot;
  • 49. JavaScript: Objects: Constructor function Cat(/*String*/ name) { this refers to the global this.name = name; object window this.talk = function() { //... } } call without new var cat2 = Cat(quot;Barsikquot;); typeof cat2 >> undefined cat2.name >> TypeError: cat2 has no properties window.name >> quot;Barsikquot;
  • 50. JavaScript: Objects: Constructor When an object is created, a special property is assigned to it behind the scenes — the constructor property. var cat = new Cat(quot;Barsikquot;); var constr = cat.constructor; var cat3 = cat.constructor(quot;Murzikquot;); constr >> function Cat(name) { .... } cat3.talk() >> quot;I’m Murzik. Mrrr, miaow!quot;
  • 51. JavaScript: Objects: call and apply Two useful methods of the function objects are call() and apply(). They allow your objects to borrow methods from other objects and invoke them as their own. var cat = new Cat(quot;Barsikquot;); //.. var cat4 = {name:quot;Chernyshquot;}; cat.talk.call(cat4/**, param1, param2, ... **/) >> quot;I’m Chernysh. Mrrr, miaow!quot; cat.talk.apply(cat4/**, [param1, param2, ...] **/) >> quot;I’m Chernysh. Mrrr, miaow!quot;
  • 52. JavaScript: Objects: instanceof operator tests if an object was created with specific constructor instanceof function. var cat = new Cat(quot;Barsikquot;); var o = {}; cat instanceof Cat >> true cat instanceof Object >> true o instanceof Object >> true o instanceof Cat >> false
  • 55. JavaScript: Prototype: Intro • not be confusing things, it’s not prototype.js library • JavaScript has prototype-based object model
  • 56. JavaScript: Prototype: prototype property function Cat(/*String*/ name) { this.name = name; this.talk = function() { return quot;I'm quot;+this.name+quot;. Mrrr, miaow!quot;; } }; the way how enumerate all properties in an object Cat.prototype >> {} (object) for(var i in Cat.prototype) { i+quot;:quot;+Cat.prototype[i] >> ${propName}:${propValue} }
  • 57. JavaScript: Prototype: Adding properties Adding methods and properties to the prototype property of the constructor function is another way to add functionality to the objects this constructor produces. var cat = new Cat(quot;Barsikquot;); Cat.prototype.animal = quot;catquot;; Cat.prototype >> {animal: quot;catquot;} cat.animal >> quot;catquot; Cat.prototype.seeADog = function() { return quot;I'm quot;+this.name+quot;. Sshhhhhhh!quot;; } cat.seeADog() >> quot;I'm Barsik. Sshhhhhhh!quot;;
  • 58. JavaScript: Prototype: Adding properties The same result as in the previous example ... var cat = new Cat(quot;Barsikquot;); Overriding the prototype Cat.prototype.animal = quot;catquot;; completely Cat.prototype = { animal: quot;catquot;, seeADog : function() { return quot;I'm quot;+this.name+quot;. Sshhhhhhh!quot;; } } cat.animal >> quot;catquot; cat.seeADog() >> quot;I'm Barsik. Sshhhhhhh!quot;;
  • 59. JavaScript: Prototype: Changing prototype var cat = new Cat(quot;Barsikquot;); var cat2 = new Cat(quot;Murzikquot;); Cat.prototype.animal = quot;catquot;; Changing the prototype for all Cat instances cat.animal >> quot;catquot; cat2.animal >> quot;catquot; Cat.prototype.animal = quot;dogquot;; cat.animal >> quot;dogquot; cat2.animal >> quot;dogquot;
  • 60. JavaScript: Prototype: Own props vs. prototype ones function Gadget(/*String*/ name) { this.name = name; } var iphone = new Gadget(quot;iPhonequot;); Gadget.prototype.name = quot;nonequot;; iphone.name >> quot;iPhonequot; delete iphone.name; iphone.name >> quot;nonequot;
  • 61. JavaScript: Prototype: Extending built-in objects Yeah, it’s possible... String.prototype.getSecondLetter = function() { return this[1]; } var str = quot;hello!quot;; str.getSecondLetter() >> quot;equot; ... but be careful.
  • 63. JavaScript: Inheritance: Prototype Chaining Example function Shape() { this.name = quot;Shapequot;; this.getName = function() { return this.name; } }; function TwoDShape() { this.name = quot;2DShapequot;; }; function Triangle(/*Number*/ side, /*Number*/ height) { this.side = side; this.height = height; this.name = quot;Trianglequot;; this.getArea = function() { return this.side * this.height / 2; } }
  • 64. JavaScript: Inheritance: Prototype Chaining Example TwoDShape.prototype = new Shape(); Triangle.prototype = new TwoDShape(); TwoDShape.prototype.constructor = TwoDShape; Triangle.prototype.constructor = Triangle; var t = new Triangle(10,4); >> 20 out(t.getArea()); >> Triangle out(t.getName()); >> function Triangle(side,height){...} out(t.constructor); out(t instanceof Triangle); >> true out(t instanceof TwoDShape); >> true out(t instanceof Shape); >> true out(t instanceof String); >> false out(Triangle.prototype.isPrototypeOf(t)); >> true out(TwoDShape.prototype.isPrototypeOf(t)); >> true out(Shape.prototype.isPrototypeOf(t)); >> true out(String.prototype.isPrototypeOf(t)); >> false var shape = new Shape(); out(shape.getName()); >> Shape
  • 65. JavaScript: Inheritance: Shared Properties Move shared properties to prototype. function Obj() { function Obj() {}; == this.text = quot;Hello this world!quot;; Obj.prototype.text = quot;Hello this world!quot;; }; But how about memory usage?
  • 66. JavaScript: Inheritance: Some profiling results Activity Monitor v. 3.0.1 Mac OS prototype property this. property
  • 67. JavaScript: Inheritance: Inheriting the prototype only function Shape() {} Shape.prototype.name = quot;Shapequot;; Shape.prototype.getName = function() { return this.name; }; function TwoDShape() {} TwoDShape.prototype = Shape.prototype; TwoDShape.prototype.constructor = TwoDShape; TwoDShape.prototype.name = quot;2DShapequot;; function Triangle(/*Number*/ side, /*Number*/ height) { this.side = side; this.height = height; } Triangle.prototype = TwoDShape.prototype; Triangle.prototype.constructor = Triangle; Triangle.prototype.name = quot;Trianglequot;; Triangle.prototype.getArea = function() { return this.side * this.height / 2; }
  • 68. JavaScript: Inheritance: Inheriting the prototype only var t = new Triangle(10,4); >> 20 out(t.getArea()); >> Triangle out(t.getName()); >> function Triangle(side,height){...} out(t.constructor); out(t instanceof Triangle); >> true out(t instanceof TwoDShape); >> true out(t instanceof Shape); >> true out(t instanceof String); >> false out(Triangle.prototype.isPrototypeOf(t)); >> true out(TwoDShape.prototype.isPrototypeOf(t)); >> true out(Shape.prototype.isPrototypeOf(t)); >> true out(String.prototype.isPrototypeOf(t)); >> false var shape = new Shape(); out(shape.getName()); >> Triangle
  • 71. JavaScript: General: Even more... • Math - mathematical constants and functions. • Date - working with dates. • RegExp - regular expressions. See more info on www.developer.mozilla.org
  • 72. JavaScript: General: Exception handling try { iDontExist(); } catch(e){ //process error here out(e); >> ReferenceError: iDontExist is not defined } finally { //do some work here }
  • 73. JavaScript: General: Exception handling • EvalError • RangeError • ReferenceError • SyntaxError • TypeError • URIError • Your own with new Error([message[, fileName[, lineNumber]]])
  • 76. DOM: Introduction The Document Object Model, a language-neutral set of interfaces. The Document Object Model is an API for HTML and XML documents. It provides a structural representation of the document, enabling you to modify its content and visual presentation. Essentially, it connects web pages to scripts or programming languages.
  • 77. DOM: Chair Construction Analogy Model API
  • 78. DOM: HTML document <!DOCTYPE HTML PUBLIC quot;-//W3C//DTD HTML 4.01//ENquot; quot;http://www.w3.org/TR/html4/strict.dtdquot;> <html> <head> <meta http-equiv=quot;Content-Typequot; content=quot;text/html; charset=UTF-8quot; /> <title>ToDo list</title> </head> <body> <div>What I need to do.</div> <p title=quot;ToDo listquot;>My list:</p> <ul> <li>Finish presentation</li> <li>Clean up my home.</li> <li>Buy a bottle of milk. (May be beer will be better?;) </li> </ul> </body> </html>
  • 79. DOM: Finding elements <input type=quot;textquot; id=quot;messagequot; value=quot;Messages goes here...quot;/> ... var msgInput = document.getElementById(quot;messagequot;); element or null <ul id=quot;listquot;> <li>Item 1</li> <li>Item 2</li> array of element or an <li>Item 3</li> empty array </ul> ... var items = document.getElementsByTagName(quot;liquot;);
  • 80. DOM: Elements <p title=quot;ToDo listquot;>My tasks</p> Node types: an HTML element - 1 an attribute - 2 a text node - 3
  • 81. DOM: Element attributes • nodeName • nodeValue • nodeType • parentNode • childNodes • firstChild • lastChild • previousSibling • nextSibling • attributes • ownerDocument
  • 82. DOM: Manipulating the DOM var item = document.createElement(quot;liquot;); var text = document.createTextNode(message); item.appendChild(text); parent.appendChild(item); parent.insertBefore(someNode, item); parent.innerHTML = parent.innerHTML + (quot;<li>quot;+message+quot;</li>quot;); parent.removeChild(item);
  • 83. DOM: Event Handlers var addBtn = document.getElementById(quot;addBtnquot;); var list = document.getElementById(quot;listquot;); if(addBtn) { addBtn.onclick = function(event) { console.log(event); var value = msgInput.value; if(value) { createListEntry(list,value); } else { alert(quot;Message is empty!quot;); } } }
  • 84. DOM: Events: Capturing and Bubbling var addBtn = document.getElementById(quot;addBtnquot;); //... addBtn.addEventListener('click', function(){ //code goes here },false); addBtn.attachEvent('click', function(){ //code goes here });
  • 85. DOM: Events: Capturing and Bubbling
  • 86. DOM: Let’s see an example ToDos application • adding tasks • deleting tasks • reordering tasks • no backend support Very early alpha ;)