Java: Class-based | JavaScript: Prototype-based |
Classes/Objects | Objects (only) |
Class definitions + Constructors | Protoypes + Constructors |
Objects created with new | Objects created with new |
Inheritance of Classes | Inheritance using Prototypes |
Cannot change class definitions at run time | Constructor/Prototype only give initial definition. Objects definition can be changed at run time |
Object = flexible container of unordered collection of named properties (and methods)
In Java: JSObject = Map<String, Object>
var student = {}
Create an empty object
student.name = "Peggy";
student.university = "USI";
student.date_of_birth = new Date();
Populate its properties
student.age = function() {
return (new Date().getTime()) –
this.date_of_birth.getTime();
}
Declare a method for the object
Use this
to access the fields of the object
if (student.age() > 18) { ... }
Call a method
this
f(x); // function call
this
= the global object
obj.m(x); // method call
this
= the object obj
new C(); // constructor
this
= the new object
onclick="m(this)" // event handler
this
= the DOM element on which the event occurs
Any function called with new
becomes a constructor
Constructor names typically begin with an uppercase letter
function Person(name) {
this.name = name;
this.age = function() {...};
return this; //not needed
}
//call the constructor
var me = new Person("Peggy");
me.age();
this
inside the constructor refers to the newly created objectOnly functions called with new
become a constructor.
What happens if you forget new?
function Person(name) {
this.name = name;
this.age = function() {...};
return this; //not needed
}
//call the function
var me = Person("Peggy");
me.age();
this
inside the function refers to the global objectvar person = {
name: "Peggy",
date_of_birth: new Date(1927,0,31),
address: {
street: 'Via Buffi',
number: 13
}
}
Objects can also be created directly using object literals following the JavaScript Object Notation (JSON)
lowercase function name
function person(name, dob) {
return {
name: name,
date_of_birth: dob,
age: function() {
return...
}
}
}
var p = person("Peggy", new Date(...));
new
not needed here!
Sometimes called factory methods
person.height = "120cm";
person.hello = function() { ... };
You can add properties and methods to an object even after it has been created
delete person.height;
Properties and methods can be removed from an object with the delete
operator
Never assume an object's field has been defined
var o = {};
if (o) { //o is defined
}
o.field = x;
if (o.field) { // o.field is defined
}
if (o && o.field) {
// both o and o.field are defined
}
1. return a new JSON object
function person(name, dob) {
return {
name: name,
date_of_birth: dob,
age: function(){...}
};
}
function student(name, dob, uni) {
var that = person(name, dob);
that.uni = uni;
that.canEnroll = function() {...};
return that;
}
var s = student(“Peggy”, new Date(...), “USI”);
if (s.age() > 18 && s.canEnroll() ) { ... }
2. Create the “super” object
3. Augment it
new
not needed here!
function person(name, dob) {
return {
name: name,
date_of_birth: dob,
age: function(){...}
};
}
function student(name, dob, uni) {
var that = {};
that.person = person(name, dob);
that.uni = uni;
that.canEnroll = function() {...};
return that;
}
var s = student(“Peggy”, new Date(...), “USI”);
//s = {person: {name: "Peggy", date_of_birth: , age: },
// uni: "USI", canEnroll: }
function class(a,b) {
// initialize the object from the superclass
var that = superclass(a);
// declare private properties
var private_c;
// declare private methods
function private_method() {...}
// declare public properties
that.public_d = b;
// declare public methods
that.public_method = function(p) {
this.public_d ... ;
private_c;
private_method();
}
return that;
}
var namespace = {};
Define a prefix to protect all your objects and functions so that their names do not conflict with others
Everything within the namespace is always visible. Use packages to separate the external public interface from the private implementation
namespace.o = {};
namespace.f = function() {};
Syntax reminder:var x = function(){}();
var package = function () {
// declare private properties
var private_c;
// declare private methods
function private_method() {...}
// declare public interface
return {
//declare public properties
public_d: 100,
// declare public methods
public_method: function(p) {
var x = p || public_d;
private_c;
private_method();
}
}
} ();
Warning: remember to call the function to instantiate the package
Manipulate an HTML document from the JavaScript code
innerHTML
)Document Object Model
<html>
<head></head>
<body>
<h1>Heading 1</h1>
<p>Paragraph.</p>
<h2>Heading 2</h2>
<p>Paragraph.</p>
</body>
</html>
This HTML string is parsed by the browser and represented as objects that can be accessed from JavaScript code
document //root of the tree
document.body //the body element node
document.body.firstChild
document.body.lastChild
document.body.childNodes[] // array of children
Navigate through the DOM tree
document.getElementById('section1');
document.getElementsByTagName('div');
Direct, random-access to specific elements
document.getElementsByClassName("section");
document.querySelector("#section1");
document.querySelectorAll("div");
document.querySelectorAll(".section");
document.querySelectorAll("table > tr > td");
New HTML5 API (Use CSS selectors in JavaScript)
The newly created elements are not connected to the document tree
document.createElement(tagName)
document.createTextNode(text)
//clone the element
node.cloneNode()
//clone the element and its descendents
node.cloneNode(true)
//Add neu as the lastChild of node
node.appendChild(neu)
//Add to the children of node before sibling.
node.insertBefore(neu, sibling)
node.insertBefore(neu, node.firstChild)
// Swap the old child element with neu.
node.replaceChild(neu, old)
old.parentNode.replaceChild(neu, old)
//remove the old child node and return it
node.removeChild(old)
//remove the old node itself
old.parentNode.removeChild(old)
//read-write the style class of a node element
node.className
//for multi-class elements (HTML5)
node.classList
//low-level access to the style properties
node.style.property
CSS properties map 1:1 with JavaScript properties (except property names that contain “-”. z-index → zIndex, background-color → backgroundColor, etc.)
N.nodeName
N.attributes
N.id
N.name
N.className
N.classList
N.style
N.innerHTML
N.textContent
DOM Tree Traversal
N.childNodes
N.firstChild
N.lastChild
N.nextSibling
N.ownerDocument
N.parentNode
N.previousSibling
//add or remove event listeners
N.addEventListener(type, listener, capture)
N.removeEventListener(type, listener, capture)
on
prefix)//more primitive
N.onclick = listener
document.addEventListener("click",
function(event) { alert(event); }, false);
document.onclick = function(event) { ... }
N.innerHTML = '<b>Text</b>';
Access the HTML Parser
//prepare the content
content = ...
//add it to the document (once)
N.innerHTML = content;
Construct the content first and later add it to the document once to minimize page redraw operations by the browser
Draw on the page from JavaScript code
<canvas id="cid" width="640" height="480"></canvas>
Define a canvas element for drawing
var c=document.getElementById("cid");
var ctx=c.getContext("2d");
Get access to the 2d drawing context
ctx.fillStyle
ctx.strokeStyle
ctx.rect()
ctx.fillRect()
ctx.arc()
ctx.moveTo()
ctx.lineTo()
ctx.fillText()
ctx.drawImage()
ctx.getImageData()
More information: https://developer.mozilla.org/en-US/docs/Canvas_tutorial
Key-value persistent storage on the browser
localStorage.key = value; //value is a string
var value = localStorage.key;
if (localStorage.key) //check if key exists
localStorage.setItem('key',value);
var value = localStorage.getItem('key');
Alternative Syntax
What if you want to store objects?
localStorage.key = JSON.stringify(object);
Convert the object into a JSON string before storing it
var object = JSON.parse(localStorage.key)
Parse the stored JSON string back into the object
Key-value temporary storage on the browser
sessionStorage.key = value; //value is a string
var value = sessionStorage.key;
if (sessionStorage.key) //check if key exists
Stored values are lost when the browser tab is closed, but will survive a page refresh
Security Note: localStorage
and sessionStorage
are implicitly scoped by the document origin. Pages downloaded from different websites cannot share data stored on the browser
Find out where the user is on the planet
navigator.geolocation.getCurrentPosition(
function(position) {
position.coords.latitude;
position.coords.latitude;
}, function(error) {
// error.code can be:
// 0: unknown error
// 1: permission denied
// 2: position unavailable
// 3: timed out
});
The first callback is called when the position has been computed. The second error handling callback is optional.
navigator.geolocation.watchPosition(function(position) {
//track the position as it changes
});
main.js
var worker = new Worker('worker.js');
worker.onmessage = function(event) {
console.log(event.data);
}
worker.postMessage('start');
worker.js
self.onmessage = function(event) {
//do some work
var data; //output
self.postMessage(data);
}
Transfer Object set by the source in the dragstart
event, read by the target in the drop
event
Use a spacebar or arrow keys to navigate