Misc
Case sensitivity
- JavaScript is case sensitive
Paradigm
- Functional programming language
- Functions are first-class objects
- Object-based language
- Based on prototypes, rather than classes
- Uses prototypal inheritance
Race conditions
Problem
- Trying to use code from a .js file that hasn’t been loaded yet
- In Internet Explorer, there's no way to control the order in which .js files are loaded
- Need to defer the calling of code from .js files until after they're loaded
Solution
- Use the "defer" keyword in a script tag
- Wait until an onload event fires before using code from the .js files
- An onload event won’t fire until after all .js files have been loaded
void operator
void(expression)
void expression
- Evaluates the expression without returning a value
- The parentheses are optional, but recommended
Timer events
setTimeout
setTimeout("javascript statements", milliseconds)
setTimeout(obj.foo, milliseconds)
- The first parameter is either a string containing JavaScript statements, or a function reference.
setTimeoutis a method of the window object.thisrefers to the window object when the code is run.
var timerVar = setTimeout("alert('hi');", 500); // Set timer
clearTimeout(timerVar); // Clear timer
setInterval
setInterval("javascript statements", milliseconds)
- Execute the specified code at recurring intervals
var timerVar = setInterval("alert('hi');", 500); // Set timer
clearInterval(timerVar); // Clear timer
Embedding JavaScript in HTML attributes
javascript:
<a href="javascript:...">...</a>
- URI protocol specifier
- Only valid in a src or href attribute
JavaScript expressions in CSS
selector { property: expression(javascript-expression); }
- Only applies to IE >= 5
.MyClass { width: expression(document.all ? 2px : 3px); }
Regular expressions
RegExpobject
String methods
match()replace()search()
Browser support
- 1.0 : NS2, IE3
- 1.1 : NS3, Op < 5
- 1.2 : NS4, IE4
- 1.3 : NS > 4.05, Op5, IE5
- 1.4 : Op6, HotJava3
- 1.5 : NS6, Gecko, IE5.5
- 1.6 : Firefox 1.5, NS7
- 1.7 : Firefox 2
Parameterizing links
- Dynamically adding URL parameters to a link
- Use the
encodeURIComponentfunction to safely encode strings that will be added to the URL
// Add the URL of the referring page to the link
function addXurlParam(id) {
var field = document.getElementById(id);
if (field) {
field.href += ((field.href.indexOf("?") == -1) ? "?" : "&") + "xurl=" + encodeURIComponent(document.location.href);
}
}
Right-click
- When the user right-clicks to open a link, by default, any related JavaScript code in the href attribute or the onclick event does not run
- Right-click events can be captured to address this problem
- This behavior is browser-specific: href="javascript:..." works fine in IE and Opera, but not Firefox; onclick="..." has the same right-click issue in all browsers
Options
href="javascript:..."
- Dynamically create the full URL using a URI protocol specifier
- Very-poor readability for the URL
- Badly hinders "copy link location" (makes the link unusable as-is; includes a parameter that's only appropriate for a specific page)
- If JavaScript is disabled, the link doesn't work
- If the user right-clicks to open the link, there are no link related options on the pop-up menu
onclick="..."
- Dynamically append the parameter to the URL using an onclick event
- Moderate readability for the URL--the parameter is only visible on the destination page
- Does not hinder "copy link location"
- If JavaScript is disabled or the user right-clicks to open the link, the parameter does not get added, but the base link still works
document.write('<a href="...">...</a>')
- Write the entire <a> tag using document.write
- Poor readability for the DHTML source code
- Poor readability for the URL--the parameter is always visible
- Hinders "copy link location" (includes a parameter that's only appropriate for a specific page)
- Works fine if the user right-clicks to open the link
- If JavaScript is disabled, the link does not appear at all
- If the link is plain text, this is one of the best options
document.getElementById(id)
- Dynamically append the parameter to the URL using the HTML DOM
- Requires adding an id to the <a> tag
- Poor readability for the URL--the parameter is always visible
- Hinders "copy link location" (includes a parameter that's only appropriate for a specific page)
- If JavaScript is disabled or the user right-clicks to open the link, the parameter does not get added, but the base link still works
- If the link is plain text, this is the safest option
POSTed form
- Use a hidden field for the parameter
- Very good readability for the URL--the parameter is never visible
- Does not hinder "copy link location"
- If the link is an image or a button, this is easily the best option
- Works fine even when JavaScript is disabled
- Related right-click options are not available for form images and buttons, so issues with right-clicking do not apply
- If the link is plain-text, this is very problematic
- By default, the form and fields do not get submitted if JavaScript is disabled or the user right-clicks to open the link; the static href is used instead
Closures
- A function reference has a hidden reference to the closure it was created in (which stores the sibling variables and functions in the definition scope).
- When a function is declared within another function, the local variables of the outer function are kept alive and are available to the inner function after the outer function returns.
- For the inner function to be accessible afterwards, an external reference to it must be kept in some way (declaring it as a global function, returning a reference to it, ...).
- Each time the outer function is called, a new closure is created.
- When multiple functions are declared within a function, all of the inner functions have the same closure (the same local variables).
// Defining and immediately invoking a function
(function(){...})();
// Returning a local reference to an inner function
var foo = (function(){
var i = 1; // Local variable in the closure
var myfoo = function() { alert(i); } // Local reference to a function in the closure
i++;
return myfoo; // Return the local function reference
})();
foo(); // 2
// Global reference to an inner function
(function(){
var i = 1; // Local variable in the closure
gfoo = function() { alert(i); } // Global reference to a function in the closure
gbar = function() { alert(i); } // Global reference to a function in the closure
i++;
})();
gfoo(); // 2
gbar(); // 2
- Closures make the code less maintainable and should be used sparingly.
- Can be useful for callback functions, so that (for instance) the request object for an Ajax call is still available when the response from the server is received.
- Closures are sometimes used in relation to event handlers.
Misc
- JavaScript is a prototype-based programming language (has objects but not classes)
- The two options for creating an object are using object literals or object templates
- Paths are relative to the current page
- Current url: document.location.href
- Setting an HTML form field: document.form-name.field-name.value
- alert("Text"); // Displays a string in a pop-up window
- eval(); // Execute code stored as a string
- In the browser address bar: javascript:...
- Firefox: about:config, about:plugins
- Can dynamically change the class of an element: elem.attributes['class'].value = '...';
- getElementById works for IE 5+ (the alternative, document.all, is only needed for IE 4.x)
- It's possible to capture a right-click event (context menu)
- To help support when JavaScript is disabled, for a dynamic or interactive UI element, display something initially that's at least minimally functional, and then if JavaScript is enabled display the full version of it
- JavaScript frameworks: Prototype, script.aculo.us, jQuery, extJS, Dojo, YUI
Resources URL:
notes/javascript/resources
Sources URL:
notes/javascript/sources