06 – Java Script (2) Informatics Department Parahyangan Catholic University.
-
Upload
brett-tyler-carpenter -
Category
Documents
-
view
217 -
download
0
Transcript of 06 – Java Script (2) Informatics Department Parahyangan Catholic University.
Pemrograman Berbasis Web06 – Java Script (2)
Informatics DepartmentParahyangan Catholic University
Object
An Object is a collection of attributes (variables) and methods (functions) that deal with related values and tasks
Simplest way to create an object in JS:var rocket = new Object();This creates a new instance of an Object, a
blank object template, and assigned it to a variable
Object - Attributes
Adding attributes :var rocket = new Object();rocket.engineCount = 2;rocket.thrust = 5000;rocket.astronautCount = 4;rocket.colour = "red";
Object
How do we make 2 rockets ?
var rocket = new Object();rocket.engineCount = 2;
var anotherRocket = new Object();anotherRocket.engineCount = 1;anotherRocket.wings = 2;
Both rocket objects are seemingly identical, however, if we outputted the number of wings on the second rocket, we’d be returned “2”, but if we did the same to the first rocket, we’d be returned “undefined”.
Object Template
Similar concept as Java’s Class’ constructor
Creating objects from a template:
function Rocket(engineCount, thrust, wings){this.engineCount = engineCount;this.thrust = thrust;this.wings = wings;
}
var rocket = new Rocket(2, 5000, 4);var anotherRocket = new Rocket(1, 2000, 2);
var creates a local variablethis. creates an attribute for this instance of
the object
Regular Function V.S. Object Template
x is assigned a foo object with name attribute equals “FOOOOO”
y is assigned a number value: 123
var x = new foo();var y = foo();
function foo(){ this.name = "FOOOOO"; return 123;}
Object - Methods
Adding methods:
Usage example:
function Rocket(engineCount, thrust, wings) {this.engineCount = engineCount;this.enginesOn = false;this.thrust = thrust;this.wings = wings;
this.turnEnginesOn = function() {this.enginesOn = true;alert("Engines are now on");
}}
var rocket = new Rocket(2, 5000, 4);rocket.turnEnginesOn();
Object - Methods
An object method is basically a function assigned to an object attribute.
functions are objects so they’re a data type and can be assigned to a variable.
The name of the method will take the name of the attribute the method is assigned to
Object – Prototype Keyword
Similar to Java’s static keyword prototype attributes / methods are
shared among all instances of the same objectfunction Rocket(engineCount, thrust, wings) {
this.engineCount = engineCount;this.enginesOn = false;this.thrust = thrust;this.wings = wings;Rocket.prototype.fuel = “Liquid hydrogen”;
Rocket.prototype.turnEnginesOn = function() {this.enginesOn = true;alert("Engines are now on");
}}
Associative Arrays
An associative array is one whose elements are referenced by name rather than by numeric offset.
balls = {"golf": "Golf balls, 6","tennis": "Tennis balls, 3","soccer": "Soccer ball, 1","ping": "Ping Pong balls, 1 doz“
}
for (b in balls)document.write(b + " = " + balls[b] + "<br />")
Array’s Methods
Creating an empty Array
concat concatenates two arrays, or a series of values with an arrayfruit = ["Banana", "Grape"];veg = ["Carrot", "Cabbage"];all = fruit.concat(veg);document.write(all);
var A = Array();
pets = ["Cat", "Dog", "Fish"];more_pets = pets.concat("Rabbit", "Hamster");document.write(more_pets);
RESULT:Banana,Grape,Carrot,Cabbage
RESULT:Cat,Dog,Fish,Rabbit,Hamster
Array’s Methods
pushinserts a new value into an array
popdeletes the last inserted value and returns it
sports = ["Football", "Tennis", "Baseball"];document.write("Start = " + sports + "<br />");sports.push("Hockey");document.write("After Push = " + sports + "<br />");removed = sports.pop();document.write("After Pop = " + sports + "<br />");document.write("Removed = " + removed + "<br />");
RESULT:Start = Football,Tennis,BaseballAfter Push = Football,Tennis,Baseball,HockeyAfter Pop = Football,Tennis,BaseballRemoved = Hockey
Array’s Methods
reverse
joinconvert all the values in an array to strings and then join them together into one large string, placing an optional separator between them.
sports = ["Football", "Tennis", "Baseball", "Hockey"];sports.reverse();document.write(sports);
pets = ["Cat", "Dog", "Rabbit", "Hamster"];document.write(pets.join() + "<br />");document.write(pets.join(' : ') + "<br />");
RESULT:Hockey,Baseball,Tennis,Football
RESULT:Cat,Dog,Rabbit,HamsterCat : Dog : Rabbit : Hamster
Array’s Methods
sort// Alphabetical sortsports = ["Football", "Tennis", "Baseball", "Hockey"];sports.sort();document.write(sports + "<br />");// Reverse alphabetical sortsports = ["Football", "Tennis", "Baseball", "Hockey"];sports.sort().reverse();document.write(sports + "<br />");// Ascending numerical sortnumbers = [7, 23, 6, 74];numbers.sort(function(a,b){return a - b});document.write(numbers + "<br />");// Descending numerical sortnumbers = [7, 23, 6, 74];numbers.sort(function(a,b){return b - a});document.write(numbers + "<br />");
Timers
timers are methods that allow us to run blocks of code once after a certain amount of time has passed, or many times after a repeating interval
Timers
Setting one-off timers
Unsetting one-off timers
function onTimeout() {alert("Ding dong!");
};var timer = setTimeout(onTimeout, 3000);
clearTimeout(timer);
Timers
Setting repeating timers
Unsetting repeating timers
function onInterval() {alert("Ding dong!");
};var interval = setInterval(onInterval, 3000);
clearInterval(interval);
JQuery
jQuery is a JavaScript library
Why are we using it? Most of the core features are apparent in
all the major browsers However, a lot of browsers implement
other features in slightly different ways. One example is detecting when a HTML
document has finished loading (more on this later)
JQuery
To use JQuery, we need to link the JQuery file into our HTML document (need to go to the jQuery website, download the library, and add it into the same folder as your HTML page.)
Second option is to use Google-Hosted version
<script type="text/javascript“ src="jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
Running JS After the page has loaded
Why can’t we just run JavaScript at any time?
Three ways: The wrong way (window.onload) The long way (The DOM) The easy way (JQuery)
Running JS After the page has loaded
The wrong way (window.onload)
window.onload is too patient. It doesn’t run until absolutely every piece of content has finished loading.
window.onload = function() {alert("Hello, World!");
};
Running JS After the page has loaded
The long way (The DOM)the DOM represents the raw structure of our content, which means it has to be created before the content is displayed on the screen. If we can find out when the DOM has finished loading, we’ll know when the content is accessible, regardless of whether it’s visible on the screen.
Unfortunately, detecting when the DOM has loaded is a troublesome task. There’s just no consistent method across all the major browsers.
Running JS After the page has loaded
// Dean Edwards/Matthias Miller/John Resigfunction init() {
// quit if this function has already been calledif (arguments.callee.done) return;// flag this function so we don't do the same thing twicearguments.callee.done = true;// kill the timerif (_timer) clearInterval(_timer);// do stuff
};/* for Mozilla/Opera9 */if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);}/* for Internet Explorer *//*@cc_on @*//*@if (@_win32)document.write("<script id=__ie_onload defersrc=javascript:void(0)><\/script>");var script = document.getElementById("__ie_onload");script.onreadystatechange = function() {
if (this.readyState == "complete") {init(); // call the onload
handler}
};/*@end @*/
/* for Safari */if (/WebKit/i.test(navigator.userAgent)) { // sniffvar _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {init(); // call the onload handler}
}, 10);}/* for other browsers */window.onload = init;
Running JS After the page has loaded
The easy way (JQuery)$(document).ready(function() {
alert("Hello, World!");});
JQuery selector
a method that does the same thing as Dean Edwards’ method
Accessing the DOM using JQueryUSING PURE JAVA SCRIPT getElementById(“blog”) getElementsByTagName(“p
”) innerHTML
USING JQUERY
$(“#blog”) $(“p”) .html()
var secondaryHeadings = $("h2");alert(secondaryHeadings.html());secondaryHeadings.html("Now we've changed the content");
Example: