View
8.651
Download
1
Category
Preview:
DESCRIPTION
Day 1 of 7-days "JavaScript and Rich User Interfaces" training for my colleagues. It's a quintessence of JavaScript Basics.
Citation preview
JavaScript Basics And DOM Manipulation
Siarhei Barysiuks.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.”
“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.”
“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.firefox.com
www.getfirebug.com
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
• number• string• boolean• null• undefined
There are five primitive data types in JavaScript:
Everything that is not a primitive is an object.
JavaScript: Primitive types
Numbers
JavaScript: Primitive types: Numbersvar n1 = 1;out(typeof n1); var n2 = 1.5;out(typeof n2);
var n3 = 0100;out(typeof n3);out (n3);
var n4 = 0xFF;out(typeof n4);out(n4);
>> "number"
>> "number"
>> "number">> 64
>> "number">> 255
JavaScript: Primitive types: Numbers
var n5 = 1e1;out(typeof n5);out(n5); var n6 = 2e+3;out(typeof n6);out(n6);
var n7 = 2e-3;out(typeof n7);out(n7);
>> "number">> 10
>> "number">> 2000
>> "number">> 0.002
JavaScript: Primitive types: Numbers
var n8 = Infinity;out(typeof n8);out(n8);
var n9 = 1e309;out(typeof n9);out(n9);
var n10 = 6/0;out(typeof n10);out(n10);
var n11 = -1*Infinity;out(typeof n11);out(n11);
>> "number">> Infinity
>> "number">> Infinity
>> "number">> Infinity
>> "number">> -Infinity
JavaScript: Primitive types: Numbers
var n12 = NaN;out(typeof n12);out(n12);
var n13 = 10 * "string";out(typeof n13);out(n13);
var n14 = 1 + 1 + NaN;out(typeof n14);out(n14);
>> "number">> NaN
>> "number">> NaN
>> "number">> NaN
{ }NaN - Not a Number.
Strings
JavaScript: Primitive types: Strings
var s1 = "some string";out(typeof s1);
var s2 = 'a';out(typeof s2);
var s3 = "10";out(typeof s3);
>> "string"
>> "string"
>> "string"
{ }Any value placed between single or double quotes is considered a string.
JavaScript: Primitive types: Stringvar s41 = "one";var s42 = "two"var s43 = s41 + s42;out(s43); var s51 = "10";out(typeof s51);var s52 = s51 * 5;out(s52);out(typeof s52); var s6 = "1";out(typeof s6);out(++s6);out(typeof s6); var s7 = "some string 1";var s71 = s7 * 1;out(typeof s7);out(s71);out(typeof s71);
>> "onetwo"
>> "string"
>> 50>> "number"
>> "string">> 2>> "number"
>> "string">> NaN >> "number"
Boolean
JavaScript: Primitive types: Boolean
var b1 = false;out(typeof b1);
var b2 = "some string";var b21 = !b2;var b22 = !!b2;out(typeof b2);out(b21);out(typeof b21);out(b22);out(typeof b22);
>> "boolean"
>> "string">> false>> "boolean">> true>> "boolean"
JavaScript: Primitive types: Boolean
var b31 = "";var b32 = null;var b33 = false;var b34 = NaN;var b35 = undefined;var b36 = 0;
if ( !b3* ) { //executes this section //... }}
All values become true when converted to a boolean, with the exception of the six falsy values:
JavaScript: Primitive types: Boolean
Some interesting comparison operations:
!= ==Non-equality comparison:
Returns true if the operands are not equal to each other.
Equality comparison: Returns true when both operands are equal. The operands are converted to the same type before being compared.
!==Non-equality comparison without type
conversion: Returns true if the operands are not equal OR they are different types.
===Equality and type comparison:
Returns true if both operands are equal and of the same type.
JavaScript: Primitive types: Boolean
Some interesting comparison operations:
var b4 = 2!="2";var b41 = 2=="2"; var b42 = 2!=="2";var b43 = 2==="2";
>> false>> true >> true>> false
Null & Undefined
JavaScript: Primitive types: Null
var nl1 = null;out(typeof nl1);out(nl1);
var nl2 = 1 + null;out(nl2);
var nl3 = 1*null;out(nl3);
>> "object">> null
>> 1
>> 0
JavaScript: Primitive types: Undefined
var u1 = {}; //try to access to nonexistent //field of the objectout(typeof u1.nonexistent);out(u1.nonexistent); var u2 = 1 + undefined; out(u2); var u3 = 1 * undefined;out(u3);
>> undefined>> undefined
>> NaN
>> NaN
Arrays
JavaScript: Arrays
var a = [1,2,3];out(typeof a);out(a);out(a[0]);out(a[5]); a[5] = "some string";out(a); delete a[2];out(a); delete a[5];out(a);
>> "object">> [1,2,3]>> 1>> undefined a[5] = "some string";>> [1,2,3, undefined, undefined,"some string"]
>> [1,2, undefined, undefined, undefined, "some string"] >> [1,2, undefined, undefined, undefined, undefined]
JavaScript: Arrays
var a2 = [[1,2,3],["string1","string2",3]];out(a2[0]);out(a2[1]); var a3 = "one";out(typeof a3);out(a3[0]);out(typeof a3[0]);out(a3[1]);
>> [1,2,3]>> ["string1","string2",3]
>> "string" >> "o">> "string">> "n"
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: ParametersA 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) { return a + b;}
var r2 = sum(1);
function sum(a,b) { return a + b;}
var r3 = sum(1,2,3,4,5);
r2 >> NaN r3 >> 3
{ }1 + undefined = NaN
JavaScript: Functions: Parameters
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);
arguments is array of parameters which function accepts.
r4 >> 28
JavaScript: Functions: ScopeVariables 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 = "local"; if(true) { out(a); var a2 = "local-if"; out(a2); } out(a); out(a2);}
>> "local"
>> "local-if"
>> "local">> "local-if"
JavaScript: Functions: Function literal notation
var func3 = function(a,b) { return a*b;
};
var f3 = func3;
Functions are like any other variable.
typeof func3 >> "function"typeof f3 >> "function" func3(2,2) >> 4 f3(3,3) >> 9
JavaScript: Functions: Built-in constructor
var func6 = new Function("a,b","return a+b;");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
(function(a,b) { out(a-b);})(5,3);
•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());}
execute(function() {return "hello, i'm anonymous function!";
});
>> "hello, i'm anonymous function!"
>> 2
JavaScript: Functions: Callback Functions
function info(){ return "this is info function.";}
function execute(func) { out(func());}
execute(function() { return "hello, i'm anonymous function!";});
execute(info);
anonymous callback function
callback function
JavaScript: Functions: Inner functions
function funcTop() {
var a = function() { out("innerFunction: do some work..."); }
out("funcTop: do some work..."); a(); }
define function
call function
•Keep the global namespace clean•Privacy
JavaScript: Functions: Scope
var r5 = "global";
function func1() { out(r5); var r5 = "local"; out(r5);}
func1();
var r5 = "global";
function func1() { out(r5);}
func1();
r5 >> undefinedr5 >> "local"
r5 >> "global"
JavaScript: Functions: Lexical scopeIn JavaScript, functions have lexical scope. This means that functions create their environment (scope) when they are defined, not when they are executed.
function func4() { var v = 1; return func5();};
function func5() { return v;
};
out(func4());
function func41() {var v = 1;
return (function() { return v;
})();};
out(func41());
>> ReferenceError: v is not defined >> 1
JavaScript: Functions: Lexical scope
Global
F
Nab
c
var a;//..function F() { var b; //.. function N() { var c; //.. }}
JavaScript: Functions: Lexical scope
Global
F
N
ab
c
var a;var N;//..function F() { var b;
//..N = function () {
var c; //.. }}
Questions?
Objects
JavaScript: Objects
var obj = { prop:1, prop2:"string", "unusual-prop":"value", 'WTF?$#!@$':{ a:"a-val" }, array: [1,2,3]};
JavaScript uses •arrays to represent indexed arrays •objects to represent associative arrays (hashes)
typeof obj >> objectobj.prop >> obj["unusual-prop"] >> "value" obj['WTF?$#!@$'].a >> "a-val"obj.array >> [1,2,3]obj["array"] >> [1,2,3]
JavaScript: Objects : Defining a new property
var obj = { prop:1, prop2:"string", "unusual-prop":"value", 'WTF?$#!@$':{ a:"a-val" }, array: [1,2,3]};
obj.prop3 >> undefinedobj.prop3 = "value3";obj.prop3 >> "value3"
JavaScript: Objects : PassingPassing objects by reference.
var obj1 = { a:"val-a"};
var obj2 = obj1; obj1.a >> "val-a"obj2.a >> "val-a" obj2.a = "val-a2"; obj1.a >> "val-a2"obj2.a >> "val-a2"
//..var obj3 = { a:"val-a"};
obj1===obj2 >> trueobj1===obj3 >> false
JavaScript: Objects: Functions
var dog = { name: "Bobik", talk: function() { return "Woof, woof!"; }, sayName: function() { return this.name; }};
dog.name >> "Bobik" dog.talk() >> "Woof, woof!"dog.sayName() >> "Bobik"
JavaScript: Objects: Constructor
function Cat(/*String*/ name) { this.name = name; this.talk = function() { return "I'm "+this.name+". Mrrr, miaow!"; }}
var cat = new Cat("Barsik");
typeof cat >> objectcat.name >> "Barsik"cat.talk() >> "I’m Barsik. Mrrr, miaow!"
JavaScript: Objects: Constructor
function Cat(/*String*/ name) { this.name = name; this.talk = function() { //... }}
var cat2 = Cat("Barsik");
call without new
typeof cat2 >> undefinedcat2.name >> TypeError: cat2 has no properties
this refers to the global object window
window.name >> "Barsik"
JavaScript: Objects: Constructor
var cat = new Cat("Barsik");
var constr = cat.constructor;var cat3 = cat.constructor("Murzik");
When an object is created, a special property is assigned to it behind the scenes — the constructor property.
constr >> function Cat(name) { .... }cat3.talk() >> "I’m Murzik. Mrrr, miaow!"
JavaScript: Objects: call and applyTwo 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("Barsik");//..var cat4 = {name:"Chernysh"};
cat.talk.call(cat4/**, param1, param2, ... **/) >> "I’m Chernysh. Mrrr, miaow!"cat.talk.apply(cat4/**, [param1, param2, ...] **/) >> "I’m Chernysh. Mrrr, miaow!"
JavaScript: Objects: instanceofinstanceof operator tests if an object was created with specific constructor function.
var cat = new Cat("Barsik");var o = {};
cat instanceof Cat >> truecat instanceof Object >> true
o instanceof Object >> trueo 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 "I'm "+this.name+". Mrrr, miaow!"; }};
Cat.prototype >> {} (object) for(var i in Cat.prototype) { i+":"+Cat.prototype[i] >> ${propName}:${propValue}}
the way how enumerate all properties in an object
JavaScript: Prototype: Adding properties
var cat = new Cat("Barsik");Cat.prototype.animal = "cat";
Cat.prototype >> {animal: "cat"}cat.animal >> "cat"
Cat.prototype.seeADog = function() { return "I'm "+this.name+". Sshhhhhhh!";} cat.seeADog() >> "I'm Barsik. Sshhhhhhh!";
Adding methods and properties to the prototype property of the constructor function is another way to add functionality to the objects this constructor produces.
JavaScript: Prototype: Adding properties
var cat = new Cat("Barsik");Cat.prototype.animal = "cat";
Cat.prototype = { animal: "cat", seeADog : function() { return "I'm "+this.name+". Sshhhhhhh!"; }}
cat.animal >> "cat"cat.seeADog() >> "I'm Barsik. Sshhhhhhh!";
The same result as in the previous example ...
Overriding the prototype completely
JavaScript: Prototype: Changing prototype
var cat = new Cat("Barsik");var cat2 = new Cat("Murzik");
Cat.prototype.animal = "cat";
cat.animal >> "cat"cat2.animal >> "cat"
Cat.prototype.animal = "dog";
cat.animal >> "dog"cat2.animal >> "dog"
Changing the prototype for all Cat instances
JavaScript: Prototype: Own props vs. prototype ones
function Gadget(/*String*/ name) { this.name = name;}
var iphone = new Gadget("iPhone");
Gadget.prototype.name = "none";
iphone.name >> "iPhone"delete iphone.name;iphone.name >> "none"
JavaScript: Prototype: Extending built-in objectsYeah, it’s possible...
String.prototype.getSecondLetter = function() { return this[1];} var str = "hello!";str.getSecondLetter() >> "e"
... but be careful.
Inheritance
JavaScript: Inheritance: Prototype Chaining Examplefunction Shape() { this.name = "Shape"; this.getName = function() { return this.name; }}; function TwoDShape() { this.name = "2DShape";}; function Triangle(/*Number*/ side, /*Number*/ height) { this.side = side; this.height = height; this.name = "Triangle"; this.getArea = function() { return this.side * this.height / 2; }}
JavaScript: Inheritance: Prototype Chaining ExampleTwoDShape.prototype = new Shape();Triangle.prototype = new TwoDShape(); TwoDShape.prototype.constructor = TwoDShape;Triangle.prototype.constructor = Triangle;
var t = new Triangle(10,4);out(t.getArea());out(t.getName());
out(t.constructor);
out(t instanceof Triangle);out(t instanceof TwoDShape);out(t instanceof Shape);out(t instanceof String);
out(Triangle.prototype.isPrototypeOf(t));out(TwoDShape.prototype.isPrototypeOf(t));out(Shape.prototype.isPrototypeOf(t));out(String.prototype.isPrototypeOf(t));
var shape = new Shape();out(shape.getName());
>> 20>> Triangle
>> function Triangle(side,height){...}
>> true>> true>> true>> false
>> true>> true>> true>> false
>> Shape
JavaScript: Inheritance: Shared Properties
function Obj() { this.text = "Hello this world!";};
Move shared properties to prototype.
function Obj() {};Obj.prototype.text = "Hello this world!";==
But how about memory usage?
JavaScript: Inheritance: Some profiling results
Activity Monitorprototype propertythis. property
v. 3.0.1 Mac OS
JavaScript: Inheritance: Inheriting the prototype only function Shape() {}Shape.prototype.name = "Shape";Shape.prototype.getName = function() { return this.name;}; function TwoDShape() {}TwoDShape.prototype = Shape.prototype;TwoDShape.prototype.constructor = TwoDShape;TwoDShape.prototype.name = "2DShape"; function Triangle(/*Number*/ side, /*Number*/ height) { this.side = side; this.height = height;}
Triangle.prototype = TwoDShape.prototype;Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = "Triangle";Triangle.prototype.getArea = function() { return this.side * this.height / 2; }
JavaScript: Inheritance: Inheriting the prototype only
var t = new Triangle(10,4);out(t.getArea());out(t.getName());
out(t.constructor);
out(t instanceof Triangle);out(t instanceof TwoDShape);out(t instanceof Shape);out(t instanceof String);
out(Triangle.prototype.isPrototypeOf(t));out(TwoDShape.prototype.isPrototypeOf(t));out(Shape.prototype.isPrototypeOf(t));out(String.prototype.isPrototypeOf(t));
var shape = new Shape();out(shape.getName());
>> 20>> Triangle
>> function Triangle(side,height){...}
>> true>> true>> true>> false
>> true>> true>> true>> false
>> 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);}finally { //do some work here}
>> ReferenceError: iDontExist is not defined
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 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.
The Document Object Model, a language-neutral set of interfaces.
DOM: Chair Construction Analogy
Model API
DOM: HTML document<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"><html> <head> <meta http-equiv="Content-Type"
content="text/html; charset=UTF-8" /> <title>ToDo list</title> </head> <body> <div>What I need to do.</div> <p title="ToDo list">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="text" id="message" value="Messages goes here..."/>
...
var msgInput = document.getElementById("message");
<ul id="list"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li></ul>
...
var items = document.getElementsByTagName("li");
element or null
array of element or an empty array
<p title="ToDo list">My tasks</p>
DOM: Elements
Node types:
an HTML element - 1an attribute - 2a 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("li");var text = document.createTextNode(message);item.appendChild(text);
parent.appendChild(item);
parent.insertBefore(someNode, item);
parent.innerHTML = parent.innerHTML + ("<li>"+message+"</li>");
parent.removeChild(item);
DOM: Event Handlers
var addBtn = document.getElementById("addBtn");var list = document.getElementById("list");if(addBtn) { addBtn.onclick = function(event) {
console.log(event);var value = msgInput.value;
if(value) { createListEntry(list,value); } else { alert("Message is empty!"); } }}
DOM: Events: Capturing and Bubbling
var addBtn = document.getElementById("addBtn");
//...
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 exampleToDos application
• adding tasks• deleting tasks• reordering tasks• no backend support
Very early alpha ;)
Questions?
Recommended