Javascript Introduction Vu Viet Phuong - Portal Tea
May 06, 2015
Javascript IntroductionVu Viet Phuong - Portal Team
2
Objective
• Help to approach Javascript easier
• Prepare to work with eXo javascript framework
3
Subject
• Characteristic of Javascript language
• OOP with Javascript
• Javascript and DOM
• Ajax
• Javascript performance
4
Characteristic of Javascript language
5
What is Javascript ?
Netscape initially introduced the language under the name LiveScript in
an early beta release of Navigator 2.0 in 1995
Some characteristics :
- Script language
- Interpreted
- Changing rapidly and Cross-platform support is not consistent
JavaScript is the most popular scripting language on the internet
6
What can We do with it ?
Provide interactive content on your Web pages(embeded in HTML page using <script> tag)
Much of its power is derived from both the built-in and document objects provided by the browser
Control Document Appearance and Content : document.write(), DOM...
Control the Browser : window.alert(); window.open(); window.close()...
Interact with the User : ability to define "event handlers"
7
What Javascript can’t do
Javascript are confined to browser-related and HTML-related tasks
→ it does not have features that would be required for standalone languages
Some lack of features :
Graphics capabilities
Reading or writing of files
Multithreading, except whatever comes implicitly from the web browser's internal
use of threads
8
Quick introduction of basic programming
JavaScript is similar to so many other languages: Arithmetic and logical operators are part of the languageFlow-control constructs such as if, while, and switch
Example :- Arithmetic Operators : + - * / % The addition operator (+) has a different behavior
when operating on strings as opposed to numbers
- Comparison Operators : > < >= <= != == === alert(“10” == 10) //display truealert(“10” === 10) //display false
- typeof operator :alert(typeof “some string”); //display string
http://www.techotopia.com/index.php/JavaScript_Operators
9
Quick introduction of basic programming
Flow control : (if-else, switch)if (expression)
statement; else
statement;
Loops : (while, do-while, for) Loop control (break and continue)
Object-Related Statements:with Statement : a shorthand notation when referencing objects
with(document) {write(“Hello World”);}
for…in : used to loop through an object’s propertiesfor (pros in document) {document.write(pros);}
http://en.wikipedia.org/wiki/JavaScript_syntax
10
Quick introduction of basic programming
Script Execution Order : interpreted line by line as it is found in the page
Case Sensitivity : JavaScript is case-sensitive: keywords, operators....
Statement Delimiters : Semicolons and Returns
Declare Variables :
- var keyword
- implicit declaration
11
Data type
Data Type :
- Primitive data types: number, string, boolean, undefined, null
- Composite types: objects, arrays, and functions
Dynamic Typing : Type is inferred from the variable’s content
var test = “10”; //It's a string
test = 10; //It's a number now
12
Data type
Automatic Type Conversion : Most powerful features of JavaScript, as well
as the most dangerous for the sloppy programmer
window.alert(“10” - 3); → result : 7
Force the conversion using methods like toString() or parseInt()
DynamicTyping.html
13
Functions
Function creation syntax : function Add(x, y)
{ var sum = x + y; return sum; }
var test = new Function(“alert('test')”);
var test = function() {alert('test')};
How to deal with arguments :
– length property
– arguments[] property
FunctionCreation.html
14
Context, Scope and Closures
Context : always be in some form on context (an object within which it's operating) the way context works is through the this variable
Closures : Inner functions can refer to the variables in their outer enclosing function
Curring effect
Hide variables from global scope
Scope : is tricky feature. In Javascript, scope is kept within functions
Context.html
Scope.html
Closures.html
http://jibbering.com/faq/notes/closures/
15
Object-Oriented Programming with JavaScript
16
Object in Javascript
Objects are the fundamental units of JavaScript
EVERYTHING except primative type in JavaScript is object
There are three object categories in JavaScript: • Native Objects• Host Objects• User-Defined Objects
17
Object creation
1. Using new Object()
employee = new Object()
employee.name = "Tim";
employee.say = function() {
alert('hello');
}
2. Using Literal Notation
employee = {
name : "Tim",
say : function() {
alert('hello')
}
};
NOT reusable- we cannot easily initialize different versions of the created object
18
Object creation
3. Object Constructor :
- Regular JavaScript function
- The difference is that, it is called via 'new' operator, without this, it just
likes other javascript method
// it to the current context function User( name ) {
this.name = name; }
// Create a new instance of that functionvar me = new User( "My Name" );
3. Object Constructor :
- Regular JavaScript function
- The difference is that, it is called via 'new' operator, without this, it just
likes other javascript method
19
Object creation
Now, since User() is just a functionwhat happens when we treat it as such?
User( "Test" );
// Since its 'this' context wasn't set // it defaults to the global 'window' alert( window.name == "Test" ); // display true
ObjectCreation.html
20
Prototype
Prototyping is the key to understanding the inheritance concept
“prototype” is a property of every function. Since constructor is also function, it's a property of constructor too
function User(){}; var test = new User();User.prototype.say = function() {alert('hello')};
test.say(); //display hello
ObjectCreation_Prototype.html
21
Inheritance
Inheritance is the ability to have properties from “Super Class”
Set prototype property of constructor to an “super class” object
→ “sub class” object will have access to “super class” properties
function SuperClass() {this.superHello = function() {alert(“super hello”)}
}function SubClass(){}SubClass.prototype = new SuperClass();
Inheritance.html
22
Encapsulation
Objects interact with each other via call method, and don't know what is happening inside
Private : only accessible to other private methods or privileged methods
function Bean() {var name = "test";
//Getterthis.getName = function() {return name};//Setterthis.setName = function(newName) {name = newName};
}
Encapsulation.html
23
Polymorphism
Polymorphism : is a programming language feature that allows values of different data types to be handled using a uniform interface
In java, we can achieve this by implementing an interface
In weakly typed languages like JavaScript, types are implicitly polymorphic
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
24
Namespace help us to avoid name conflic
Javascript, natively doesn't provide namespace feature
Namespacing
Workaround for this :
var = { DOMUtil : { },
….};
//After define DOMUtil, we use it in namespace like thateXo.core.DOMUtil = new DOMUtil() ;
Namespace.html
25
Javascript and DOM
26
DOM : Document Object Model
Dom is programming interface for HTML and XML documents
It provides a structured representation of the document
Javascript and DOM
<html><head>...</head><body>
<h1>Hello World!</h1></body>
</html>
// Does not work! → text is also consisdered a node document.documentElement.firstChild.nextSibling.firstChild
DOMExample.html
27
There are a number of possible values
The three that you’ll encounter the most are the following:
Element (nodeType = 1), Text (3), Document (9)
Node types
http://www.javascriptkit.com/domref/nodetype.shtml
28
API
document and window objects are the objects whose interfaces you generally use most often in DOM programming
window object represents the window itselfwindow.alert(); window.open(); window.scrollTo()
document property of window points to the DOM document loaded in that window
http://www.w3schools.com/jsref/obj_window.asp
29
document
The document provides methods for creating and manipulating all of the document's child nodes, or elements
Creating and Retrieving elements: document.getElementById(id), document.createElement(name)
Get and Set Attributes:document.getAttribute(name), document.setAttribute(name,val)
https://developer.mozilla.org/en/Gecko_DOM_Reference
Document.html
30
CSS
There are two problems that you encounter when working with CSS properties on DOM elements
Second, can't get pre-set style. We must get the computed style
First, JavaScript requires that you specify the unit of size for setting any dimensional property
document.getElementById(“table”).style.width = “200px”;
StyleTest.html
31
DOM Event
Events are actions on DOM that can be detected by JavaScript
Every element on a web page has certain events which can trigger JavaScript functions
Examples of events:
- A mouse click - A web page or an image loading - Mousing over a hot spot on the web page
32
Event Phases
Javascript events are executed in 2 phases
Capturing : event moving down the DOM tree to the element that instantiated event
Bubbling phase traverses up DOM tree to the root element
Bubbing.html
Capturing.html
33
Event object
Contains contextual information about the current event
IE’s implementation is different from the W3C’s specification
function eventHandler(evt) {var e = window.event || evt;...
}
Default behaviour : Browser has some default actions that will always occur
click <a> element → redirect to other pagepress key on textbox → display chars on textbox
34
Control event
Overriding the Browser’s Default Action :if ( e && e.preventDefault )
e.preventDefault();else
//IEwindow.event.returnValue = false;
Stop bubbling : if ( e && e.stopPropagation )
e.stopPropagation();else
window.event.cancelBubble = true;
OverrideDefaultAction.html
StopBubbling.html
35
Event handler
Traditional Bindingdocument.body.onclick(handler);
W3C method of binding event handlersdocument.body.addEventListener('click', handler, false);
IE’s methoddocument.body.attachEvent('onclick', myKeyPressHandler);
https://developer.mozilla.org/en/DOM/event
Ajax
37
Definition
Ajax (Asynchronous JavaScript and XML)
AJAX uses a combination of:
DOM
XMLHttpRequest
XML is sometimes used as the format for transferring data between the
server and client, although any format will work
38
How it work
Request process can be handled asynchronously Then a SMALL portion of desired results can be loaded upon completion
39
Make request
Create XMLHttpRequest Object- Internet Exployer 5, 6:
new ActiveXObject("Microsoft.XMLHTTP");
- IE7+, Firefox, Chrome, Opera, Safari : new XMLHttpRequest();
Establishing a Connection : GET or POST request// Open the socket ajx.open("GET", "/some/url", true); // Establish the connection to the server ajx.send();
40
Send data Serializing Data:
function User() { name: "John", last: "Resig" }
// Serialized form serObj = name=John&last=Resig
Request method : GET ajx.open("GET", "/some/url?" + serObj, true); ajx.send();
Request method : POST ajx.open("POST", "/some/url", true);ajx.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
ajx.send( serObj );
41
Handle response
readyState property : request lifecycle 0 : uninitialized
1 : connection establised2 : request received3 : processing4 : finished
• onreadystatechange property
Successful response codes: 200 <= ajx.status < 300Not modified response : 304 (Safari : undefined)Every other codes will be considered error
42
Update UI
Reading the Resulting Data
responseXML : This property will contain a reference to a precomputed DOM document
responseText : This property contains a reference to the raw text string of data returned
by the server
ajx.onreadystatechange = function(){ if ( ajx.readyState == 4) {
if (ajx.status >= 200 && ajx.status < 300) {var scores = document.getElementById("testDiv"); scores.innerText = ajx.responseText;
}}
};
Example
http://www.learn-ajax-tutorial.com/
Javascript Performance
44
Some tips
DOM access : Interaction with the DOM is usually slower than normal JavaScript code
for-in loops : most JS environments have slow implementation
eval and Function constructor : avoid using because overhead is involved in script evaluation
//expensive operationsvar func = new Function(“alert('test')”);
Pass functions, not strings, to setTimeout() and setInterval()
http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices