Except where otherwise noted, the contents of this document are
Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst.
All rights reserved.
Any redistribution, reproduction, transmission, or storage of part
or all of the contents in any form is prohibited without the author's
expressed written permission.
this.fieldName// access field
this.fieldName = value; // modify field
this.methodName(parameters); // call method
all JavaScript code actually runs inside of an object
by default, code runs in the global window object (so this === window)
all global variables and functions you declare become part of window
the this keyword refers to the current object
Event handler binding
window.onload = function() {
$("textbox").observe("mouseout", booyah);// bound to text box here$("submit").observe("click", booyah);// bound to submit button here
};
function booyah() { // booyah knows what object it was called onthis.value = "booyah";
}
event handlers attached unobtrusively are bound to the element
inside the handler, that element becomes this (rather than the window)
function processDucks() {
if ($("huey").checked) {
alert("Huey is checked!");
} else if ($("dewey").checked) {
alert("Dewey is checked!");
} else {
alert("Louie is checked!");
}alert(this.value + " is checked!");
}
if the same function is assigned to multiple elements, each gets its own bound copy
function delayMsg() {
setTimeout(booyah, 5000);
document.getElementById("output").innerHTML = "Wait for it...";
}
function booyah() { // called when the timer goes off
document.getElementById("output").innerHTML = "BOOYAH!";
}
setInterval example
var timer = null;// stores ID of interval timer
function delayMsg2() {
if (timer == null) {
timer = setInterval(rudy, 1000);
} else {
clearInterval(timer);
timer = null;
}
}
function rudy() { // called each time the timer goes off
document.getElementById("output").innerHTML += " Rudy!";
}
Passing parameters to timers
function delayedMultiply() {
// 6 and 7 are passed to multiply when timer goes off
setTimeout(multiply, 2000, 6, 7);
}
function multiply(a, b) {
alert(a * b);
}
any parameters after the delay are eventually passed to the timer function
doesn't work in IE6; must create an intermediate function to pass the parameters
why not just write this?
setTimeout(multiply(6 * 7), 2000);
Common timer errors
many students mistakenly write () when passing the function