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.
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;
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
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
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 //..
}
}
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.
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?
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.
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
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
});