Friday, 6 February 2009

Advanced JavaScript by Chuck Easttom

Few days before I started reading Advanced JavaScript Third Edition by Chuck Easttom.

It was very good book and I found the arrays chapter to be very interesting...

I would like to share few quotations from the book.

JavaScript is an easy-to-use object-oriented scripting language designed for creating dynamic online applications that link together objects and resources on both clients and servers. While Java is used by programmers to create new objects and applets, JavaScript is designed for use by HTML page authors and enterprise application developers to dynamically script the behavior of objects running on either the client or the server.

JavaScript’s design and concepts represent the next generation of software for the Internet. JavaScript is:

1. Designed for creating network-centric applications
2. Complementary to and integrated with Java
3. Complementary to and integrated with HTML
4. Open and cross-platform

This means that JavaScript works hand in hand with HTML, and will work on any platform (Windows, Linux, Mac, etc.). It is also important to note that you don’t need any special tools to use JavaScript. You can simply write scripts in any text editor, as we will do throughout most of this book.

With JavaScript, an HTML page might contain a form that processes data on the client side. A server-side JavaScript might pull data out of a relational database and format it in HTML on the fly. A page might contain JavaScript scripts that run on both the client and the server.

JavaScript supports most of Java’s expression syntax and basic control flow constructs. The only difference is the variable declaration.

JavaScript and Java are both based on objects, but their implementations differ. In both languages, many built-in functions are implemented as properties and methods of various objects.

JavaScript resembles Perl in that it is interpreted, not compiled. Java is referred to as a compiled language. Unlike most other programming languages, though, Java is not compiled to a native machine code, but rather to a Java byte code.

Both Java and JavaScript are based on objects. However, their implementations of objects are different. JavaScript is an object-based language. It supports built-in, extensible objects, but no classes or inheritance. Its object hierarchy is not an inheritance hierarchy as in Java. JavaScript features two types of objects:

Static objects — objects that combine general functions (methods) and data constructs (properties). The values of such objects’ properties are usually read-only. A static object is a single object, and thus does not enable you to create instances of it. For example, the Math object in JavaScript is a static one, because you cannot create instances according to its template.

Dynamic objects — objects by which instances are created. A dynamic object resembles a template. You do not touch or use the object directly. In order to take advantage of such an object, you must create an instance of it.

JavaScript’s object model is somewhat simpler than Java’s equivalent, so JavaScript’s object implementation is much easier to accommodate than Java’s model.

Another difference between Java and JavaScript is their time of binding. JavaScript features dynamic binding, so all object references are checked at run time. Java, on the other hand, is based on static binding, meaning that all object references must exist and be valid at compile time.

Another difference between Java and JavaScript is that Java is strongly typed, as opposed to JavaScript, which is loosely typed. That is, when you declare a variable in Java, you must specify its data type. For example, when you create a variable to contain integer values you must use the int keyword. In JavaScript, all variables are declared in the same way.

A very important difference between Java and JavaScript is that JavaScript is integrated with, and embedded in, HTML.

Internal Scripts:
The

<SCRIPT>
tag is used to enclose JavaScript code in HTML documents.
This is probably the most common method for inserting JavaScript into HTML documents.

External Scripts:
Using

<SCRIPT>
tag, which enables the use of external scripts; that is, you can use a JavaScript script that is located in another file.
Some people prefer to have their scripts in external files for a few reasons. First, your script is not as immediately and easily viewable as your HTML.
Also, some web developers have common scripts they use on multiple pages.
External scripts are useful when you need to integrate a long, sophisticated JavaScript script into an HTML file.

But we have some disadvantages too..
No back references: JavaScript scripts are mainly driven by user-initiated events. A click on a button calls a function, a selection of a form element executes another function, and so on. If you design your entire script in an external file, you will have difficulties in referring to the HTML definitions in the original file. For this reason, place only general functions in an external script.

Additional processing: The JavaScript interpreter evaluates all functions found in your script header, including those defined in the external file, and stores them in memory. Loading unneeded functions in an external file degrades the script performance.

Additional server access: You know how irritating it is to wait until another page loads in the window, especially with slow connections. That is the problem with the SRC attribute. When the browser comes across the tag that tells it to interpret JavaScript code in another file, it must first load that file. Such an action is time consuming. Most programmers say that efficiency is not as important as maintainability and clarity. However, with web page development, appearance is everything and a slow-loading web site is unlikely to be successful. Always keep in
mind that unnecessary HTTP hits to the server should be avoided.

JavaScript-only files should have the filename suffix .js, and the server must map the .js suffix to the MIME type application/x-javascript, which it sends back in the HTTP header. If the server does not map the .js filename extension to application/x-javascript, Navigator will not properly load the JavaScript file specified by the SRC attribute. In short, your server must be configured to reflect the proper MIME type; otherwise, the browser does not respond properly with the data coming back in the HTTP response to the SRC-initiated request.

There are four specific data types in JavaScript: numbers, strings, Booleans, and null values.As opposed to other languages, a variable data type is not declared explicitly but rather implicitly according to its initial value assignment. Also unique to JavaScript, there is no explicit distinction between integers and real-valued numbers.

The Value Null
The value null is often used to initialize variables that do not have any special meaning. You assign it to a variable using the standard assignment statement:

var name = null

The null value is special in that it is automatically converted to initial values of other data types. When used as a number it becomes 0, when used as a string it becomes "", and when used as a Boolean value it becomes false. Since the source of many JavaScript errors is uninitialized variables, one of the common debugging techniques is to initialize all uninitialized variables, including the meaningless ones, with a null value.
The JavaScript interpreter uses the null value on two occasions:
(1) built-in functions return null under certain circumstances, and
(2) nonexistent properties evaluate to null.
When checking for a null value, you should check if it is false or if it is equal to null.

Type Conversion

In JavaScript data types are converted automatically as needed during the course of script execution. This can be quite convenient, and many other programming languages do not allow this. A variable may hold a numeric value at one point of the script and a string at another. The following statements constitute a valid JavaScript script:

var myVar = 12
myVar = "university"

An object’s properties hold its data. Obviously you will want to refer to that data at some point, either to put new data in or to get out what the object’s property contains. You can refer to properties using the following syntax:

objectReference.propertyName

objectReference is the name of the object that the property belongs to, or any other valid reference to the object.

A dot separates each object from its property. A hierarchical object structure, with objects and properties at different levels, uses the same
syntax:

object1.object2Property1.object3Property2.property3

Notice that all the elements in the middle are both objects and properties.

Another important concept is that a property belongs to an object, and to only one object. Different objects may have properties of the same name and type, but they are not the same property.

A variable may be named exactly like a property of an object. This is possible because properties are not of the same scope as variables.
However, a variable cannot have the same name as an object at the same level. For example, the statement var a = a.b.d is not valid (actually it is valid, but the value of a is lost).

You can refer to properties and methods using either the “dot” syntax or the array notation. In array notation, square brackets replace the dots. For example, the following expression refers to a.b.d:

a["b"]["d"]

You can use the array notation for both properties and methods. The general syntax is:

objectReference["propertyName"]
objectReference["methodName"]([arguments])

It is important to understand this alternative syntax, because you cannot always use the traditional dot syntax. For example, the first character of a property name cannot be a digit when using the dot syntax. When you create an array using the built-in Array object, you can only refer to the elements of the array via the array notation (e.g., myArray[0], myArray[99]). You must always use double quotes when you refer to a property of an object that is not an array. Here are some examples for using the array notation to reference methods and properties:

document["write"]("hello!")
window["alert"]("howdy!") // note: alert() == window.alert()
Math["PI"]

Sometimes you can only use the array notation. Suppose the variable str holds the string "write". You can use the following syntax instead of document.

write():
document[str]()

An object does not inherit from other objects, but it can be contained by another object if it is a property of that object.

JavaScript is completely based on dynamic binding. That is, object references are checked at run time.

The following script’s output might surprise you a little:

var num = 4
function funct1()
{
alert(num)
var num = 2
}
funct1()

will give alert message saying 'undefined'.

The term “undefined” means that a variable does not have a value at the desired point, although it has previously been declared. Generally speaking, JavaScript scans the entire script before any execution begins. During this scan, also called parsing, JavaScript evaluates each line of code, testing it for basic syntax errors. It also determines the scope of each variable, regardless of whether or not it is in a function. If it encounters a variable declaration with the keyword var, that variable is considered local, even if a global variable with the same name exists. A variable’s scope can be either the entire script or just one function. In the preceding script segment, a global variable num is declared by initializing it to 4. The function consists of one local variable declaration. Note that the variable num inside the function has no
connection to the global variable num. The function is executed, as usual, from top to bottom. The first statement instructs JavaScript to display the value of num, the local variable inside the function. JavaScript already knows that the local variable is declared inside the function, so it does not generate an error. However, at that point, the variable does not retain any value, so it is undefined.

If you declare global variables inside a function, you must assign an initial value to the variable; otherwise, JavaScript returns an error. The
following script segment and screen capture demonstrate this fact:

function foo()
{
// local variable declarations
var a // without initialization
var b = 0 // with initialization
// global variable declarations
c // without initialization — error!
d = 0 // with initialization
}
foo()

// Runtime error occurs.

Using the arguments Array

JavaScript supports functions that accept a variable number of arguments. The first argument is functionName.arguments[0], the second one is
functionName.arguments[1], the third one is functionName.arguments[2], and so on. The number of arguments handed to the function is
stored in the length property of the arguments object:

functionName.arguments.length

The following script demonstrates this concept:

function calc()
{
document.write("The first argument is ", calc.arguments[0], "
")
document.write("The fourth argument is ", calc.arguments[3], "
")
document.write("There are ", calc.arguments.length, " arguments
")
}
var company = "Yahoo"
calc(2, 999, "internet", company, 0.0)

The script’s output is:

The first argument is 2
The fourth argument is Yahoo
There are 5 arguments

The division operator also performs the usual arithmetic conversion. However, since JavaScript is loosely typed, this operator does not act exactly as in C, Perl, Java and other strictly typed programming languages. In those languages, integer division is different from floating-point division in that the result of integer division is always an integer number. JavaScript, on the other hand, does not explicitly distinguish between integers and real-valued numbers, and therefore, the result of a division operation is not guaranteed to be an integer number. In fact, most floating-point numbers are the result of a division operator. While debugging a script, it may be helpful to remember
that the division operation in JavaScript generates the same value as your pocket calculator. You should also remember that the remainder of a
division operation is never discarded.

When the operands are floating-point numbers and cannot be represented in binary notation, division expressions often evaluate to inaccurate
results.

3 / 4 // evaluates to 0.75
3.6 / 0.1 // evaluates to 36
–20 / 4 // evaluates to –5
11.1 / 2.22 // evaluates to 4.999999999999999


Data Type Operator

typeof operand1
or
typeof (operand1)

JavaScript provides an operator to check the data type of its operand. The operand can be either a literal or a data structure such as a variable, a function, or an object. The operator returns the data type. The expression includes the word typeof followed by the literal or identifier. Here are some examples:

typeof foo == "undefined" // when foo is undefined
typeof eval == "function" // eval is a built-in function
typeof null == "object" // null is an object
typeof 3.14 == "number"
typeof true == "Boolean"
typeof "a string" == "string"
// all of the expressions are true, of course

The typeof operator is very useful for debugging. Until strong debugging tools are available, you must do all debugging by hand, and detecting the data type of a structure is sometimes essential.

Events :
Events are actions that occur in response to a specific user action on the web site. For example, clicking on a form element will trigger a click event. The events occur regardless of whether you provide code to respond to them. JavaScript provides you with a method to respond to these events and to take action based on them. In this way your web page becomes very dynamic, responding to user interaction.

Not all actions that take place in your browser are events. Events are only actions that occur in the area of the HTML page, such as loading images and selecting form elements. If an action occurs directly in the boundary of the browser’s display zone, it is an event as well. In short, an event is only concerned with action on the web page itself, not on the browser.

Event Handlers
Event handlers correspond to their associated events. They are functions that execute automatically when events occur. Many JavaScript functions are called by event handlers. You saw earlier that events are actions that do not have any direct influence; they only serve the event handlers. Each event handler is associated with an event.

Arrays in Javascript:

I found this topic very intresting

In JavaScript, specifying the length of the array or the number of elements is not vital. An array is an object like any other object. There is no explicit array type in JavaScript.

Here are some arrays:

var day = new Array(31)
var month = new Array(12)
var year = new Array() // number of years "not known"

All elements of an array are initially null. This is important because such elements do not have any influence on your script. An element with a null value actually does not exist.

Strongly typed programming languages require that you specify the number of elements in an array. In such languages all elements of an array
must contain values of the same type (int, char, …). An array is an explicit data structure in those languages. From the moment an array is declared, it takes up the required storage area in memory. It does not matter if you initialized its values or not. JavaScript, however, does not require you to initialize the elements in an array when you create it. Theoretically, if you created an array without specifying the number of elements, it would be as if you created one with zero elements. Extending an array in such languages is usually not possible; therefore, you must specify the length in all array declarations.

The null value is given by default to each element of an array in JavaScript. When the value is null, the element is not stored in the computer’s memory. So creating an array with an infinite number of elements is fine in JavaScript. However, doing so is not recommended since it would be confusing to people who read your code, and not particularly useful. Keep in mind that elements holding a null value do not take up space in memory, but they are considered elements in the array, so they are added to the array’s length property.

With JavaScript (unlike C++), it doesn’t matter whether the elements of an array are of the same data type. They can be a mix of numbers, strings, Boolean values, objects, and even arrays (which are actually objects).

Referring to an Array’s Elements Creating an array is fine, but you must be able to use it. To use an array, whether you are putting data in or taking it out, you need to access the elements of that array. Keep in mind that arrays in JavaScript are objects. Like all other objects, they have properties and methods:

arrayObjectName[subscript] // ar1[4]

The subscript follows the array name and is enclosed in square brackets. Subscripts are simple integers that start at zero.

Here is a simple array:

var ar = new Array(5)

This array has five elements: ar[0], ar[1], ar[2], ar[3], and ar[4].

After you create an array you can increase its length by specifying a value for the highest subscript element. The following code creates an array of length zero, then assigns a null value to element 99. This changes the length of the array to 100.

accounts = new Array() // array of zero elements
accounts[99] = null // array of 100 elements

Note that the array does not take up any storage space, even after it is extended.

Creating Dense Arrays

Recall that we stated earlier that you need not initialize the elements in an array before you use it. However, nothing says you cannot initialize them. This is often referred to as a dense array. A dense array is one in which each element has a value. You can construct a dense array of two or more elements starting with index (subscript) 0, if you define initial values for all elements. They are very popular in many scripting languages. You can populate an array by specifying the values of its elements:

var bb = "baseball"
var sports = new Array("football", bb, "basketball", "soccer")

You can refer to the elements of this array with the common syntax:

sports[0] == "football"
sports[1] == "baseball"
var val = 2
sports[val] == "basketball"
sports[3] == "soccer"

Array Types

You must keep in mind that JavaScript is a loosely typed language. It should not be surprising, therefore, that elements of an array can be of different types. Some elements of a given array can be strings, while others can be numbers, Boolean values, and even objects. Basically, there are five types of arrays:

1. String arrays
2. Number arrays
3. Boolean arrays
4. Object arrays (including null arrays, because null is an object)
5. Mixed arrays

Sometimes you want to know what type of array you are dealing with. JavaScript does not include any tool to facilitate this. However, using a prototype we can add a property to all arrays (remember, arrays are objects by which you can create instances) that will return the type of the array. Here is the desired method:



We can improve the efficiency of the above function by changing the loop statement.



The improvement in this function is the type of loop used.

The for...in construct loops only through the existing properties, or elements, not including the null ones. The function works just like the previous one.

At first, the data type of the first element of the array is assigned to arrayType. In every iteration of the loop, if a different type of element is found, the value of arrayType is changed to "mixed" because at least two different data types have been found in the array. Once a "mixed" array is detected, the loop is immediately terminated using a break statement.

Sometimes you want to refer to all elements of a uniform-type array. The following method is designed to be a prototype of the Array object,
returning an array of element subscripts where the specified value has been found. Here is the method:

function getSubscripts(type)
{
var ar = new Array()
var arSub = 0
for (var i = 0; i < this.length; ++i){
if (typeof this[i] == type){
ar[arSub] = this[i];
++arSub;
}
}
return ar
}

Array.prototype.getSubscripts = getSubscripts

Array Properties
Although you can add your own properties to the Array object, not all tasks can be achieved by high-level programming via JavaScript. The only built-in property of the Array object is length. Fortunately, this is also the most commonly needed property for any array. When you create an instance of an object (an array), the number of properties (elements) is stored in the length property. You can refer to it as a regular property.

Array Methods

JavaScript features a number of methods, three of which are built-in methods:

1. join()
2. reverse()
3. sort()

chop()
The chop() method chops off the last character of all strings that are elements of an array. Here is an example:

function chop(){
for (var i in this){
if (typeof this[i] == "string")
this[i] = this[i].substring(0, this[i].length – 1)
}
}

Array.prototype.chop = chop

// EXAMPLE
var line = new Array("red", "green", "blue");
line.chop();
document.write(line.getList(" "));

The script’s output is:
re gree blu

The general syntax is:
arrayInstance.chop()

grep()

The term “grep” is borrowed from the Unix world where grep is a standard search function. We use that same concept here in JavaScript. The grep() method evaluates the expression (expr) for each element of the array. It returns another array consisting of those elements for which the expression evaluated to true (the pattern was matched). To understand this method you should know that if string2 is found in string1,
string1.indexOf(string2) is not equal to –1. Here is the method:

function grep(str){
var ar = new Array()
var arSub = 0
for (var i in this){
if (typeof this[i] == "string" && this[i].indexOf(str) != –1){
ar[arSub] = this[i];
arSub++;
}
}
return ar;
}
Array.prototype.grep = grep
var line = new Array("mask", "Mascot", "mine", "amass", "hot")
document.write(line.grep("mas").getList(" "))
document.write("
")
document.write(line.grep("mas").length)

The output of this script is:
mask amass
2

The general syntax is:
arrayInstance.grep(expr)

Like this you can keep on writing your own prototypes... and add methods and properties dynamically.

Associative Arrays:
Associative arrays use strings as subscripts. For example, an element of the array can be:
color["yellow"] = "FFFF00"

Such arrays group together related data. These arrays are actually objects, except that you use square brackets instead of a dot. Another important difference is that array specification (square brackets) enables you to refer to the value of a variable as the property of method specification rather than the actual literal. For example:

var col = "yellow"
color[col] = "FFFF00"
Here is another interesting example:
var w = "write"
document[w]("Hello!") // prints "Hello!"

If you replace the array notation with the regular dot specification you receive an error:

var w = "write"
document.w("Hello!")

The dot notation requires the actual literal specified, as it does not evaluate the written value. You can use associative arrays to create nested objects resembling multidimensional arrays. For example, you can create an associative array where its subscripts are names of students in a class, so each element of the associative array is an object containing fields such as the student’s grade, age, and so on.

Note that associative arrays cannot be created as instances of the built-in Array object. You must use a constructor function to create one.
Here is an example using students:

function studentClass(){
for (var i = 0; i < arguments.length; ++i){
this[studentClass.arguments[i]] = new student()
}
}

function student(){

// this.grade = null
// this.age = null

}

var students = new studentClass("Bob", "John", "Frank", "Alfred","Sheila", "Mary")


students["Bob "].grade = 40
students["John "].age = 11
students["Frank "].grade = "N/A"
alert(students["Frank "].grade)

Creating an associative array is not difficult. Array elements are created according to the names of the students accepted as parameters by the function studentClass(). The second function is rather strange—it contains no statements. When you create an instance you can use an “empty” constructor function. You may recall from an earlier discussion that objects may be extended by simply assigning values to them. So, the statement this[studentClass.arguments[i]] = new student() just makes sure each element of the associative array is an object. The global statements later create the properties simply by assigning them values.

Another important concept to remember is that associative arrays are not explicit arrays. You can also refer to them using the dot syntax, as in:

students.John.age

The Date Object in Javascript

JavaScript comes with a built-in Date object that allows you to easily work with date and time data and related functions. Both dates and times in JavaScript are derived from the Date object, which behaves much like any other object. To implement the current date or time in your script, you must first create a new instance of the object. You can then extract the desired data from that particular instance. JavaScript handles dates in a manner very similar to Java. Many methods are implemented in both languages, resulting in an observable parallelism.

var dateInstance = new Date()

JavaScript provides JavaScript programmers with a variety of methods to deal with instances of the Date object. However, extracting and manipulating their data makes them one of the most important elements of the language.

getYear()
getMonth() //0 to 11
getDate()
getDay() //Sunday, Monday, Tuesday,...
getHours()
getMinutes()
getSeconds()
getTime()

//setters for the above...

& many more methods.

Time-Related Methods of Other Objects

setTimeout()

The setTimeout() method evaluates an expression after a specified number of milliseconds have elapsed. Its general syntax is:

timeoutID = setTimeout(expression, msec)

timeoutID is an identifier used to identify the current timeout. expression is a string expression or property of an existing object. It is
normally a simple statement that is to be executed after the specified time has ticked off.

msec is a numeric value, a numeric string, or a property of an existing object in millisecond units.

The setTimeout() method evaluates an expression after a specified amount of time. Take a look at the following example:


<HTML>
<HEAD>
<TITLE>setTimeout() method</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function displayAlert()
{
alert("5 seconds have elapsed since the button was clicked.")
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Click the button on the left for a reminder in 5 seconds;
click the button on the right to cancel the reminder before
it is displayed.
<P>
<INPUT TYPE = "button" VALUE = "5-second reminder"
NAME
= "remind_button"
onClick
= "timerID = setTimeout('displayAlert()',5000)">

</FORM>
</BODY>
</HTML>


When you click the button, the event handler’s script sets a timeout. The timeout specifies that after 5,000 milliseconds, or five seconds, the function displayAlert() is called. Therefore, five seconds after you click the button an alert box is displayed.

This method does not repeatedly execute the specified statement. That is, it does not execute it every five seconds. When the time limit specified has ticked down, the statement is executed and the timeout does not exist anymore. setTimeout() is a method of the window or frame object, depending on the basic structure of the HTML document it is used in.

and also we have some math related methods also like parseInt(), parseFloat() also.

and also we have some string functions like... charAt(), indexOf(), substring(), toString()

The Document Object Model

The Document Object Model (DOM), one of the most powerful tools available to a web developer, is a hierarchy of objects that represent the web
browser, the browser’s history, the currently loaded web page, and other important elements.

hierarchy in DOM is...
1. Window
1.a.navigator
1.b.screen
1.c.history
1.d.location
1.e.document

The window Object

The window object is at the top of the DOM hierarchy. This object represents the browser window. You will find that you don’t often deal directly with the window object, but rather as the container for the other objects you use directly on a regular basis. This doesn’t mean that you never use the window object directly, merely that it is not as commonly used as other objects.

The window object contains properties that apply to the entire window. For example, the status bar of the browser is a property of this object. It also includes a property that is actually the object itself.

few examples of ways you might use the window object.

var newwindow = window.open("http://www.chuckeasttom.com") //Open a new browser
window.newwindow.focus //Set focus to that window.
newwindow.close //Close that window.


The navigator Object

This object provides information about the browser being used. This can be quite useful in gathering information about people who visit your web site. In fact, the amount of information you can derive from this object is really rather astounding.

some of the methods and properties of the navigator object.

appName //The name of the end user’s browser.
appVersion //The version number of the end user’s browser.
cookieEnabled //Whether or not the end user’s browser has cookies enabled.
platform //The end user’s operating system.
javaEnabled() //A method that returns a Boolean telling if the browser has JavaScript enabled.

The document Object

By far the most useful object of the DOM is the document object. It contains properties for the current page loaded in the window. The properties of this object are content-dependent because each and every page has its own outline and elements. Almost everything in the page is a property of the document object, including links, images, forms and their elements, anchors, and more. Because each frame is a window (window object), it contains a document object as well. Even the background and the title are properties of this object.

write() //This is a very commonly used method and writes to the HTML page whatever is passed to the write function.
fileCreatedDate //This property shows when the loaded HTML file was created.
linkColor //This property shows the color of HTML links in the document. It is specified in the BODY tag.
open() //This method opens a new document in a new window.
embeds //An array containing all the plug-ins in a document.

The history Object

The history object is also a property of the window object. It contains properties of the URLs the user has previously visited. This information is stored in a history list, and is accessible through the browser’s menu. If the document consists of child documents in frames, each frame has its own history list, or history object. This object also contains methods enabling you to send the user’s browser to a URL found in the history list.

some of the history object’s most important properties and methods are below.

current //The current document URL.
previous //The URL of the last document in the history list.
next //The URL of the next document in the history list.
length //The number of entries currently stored in the history object.

The location Object

The location object contains properties of the current URL. Although you may think of URLs as simple standard structures, they are far more than
that. There are many types of protocols and various sections in every URL. There are also optional sections in the URL, such as anchor names and queries.

host //The URL hostname and port.
href // The entire URL.
port //The port being used.
search //The URL query string section (i.e., the section after and including the question mark).
reload //The location.reload method forces a reload of the window’s current document.
replace //The replace() method is also a property of the location, or window.location, object. It overwrites the current history entry with the specified URL.


Each property of the location object represents a different portion of the URL. The following syntax of a URL shows the relationship between the object’s properties:

protocol//hostname:port pathname search hash

Since the Document Object Model is a W3C specification, this means its behavior and usage are not dependent on a particular vendor. The DOM should be the same with Internet Explorer, Mozilla, or any browser. An important objective for any W3C standard and for the Document Object Model is to provide a standard that can be used in a wide variety of environments and applications. The DOM is designed to be used with any programming language.

Hope it will be useful...

Class Loaders in Java

Yesterday I was to know about Class Loaders and I found it very interesting. I would like to share with you the same.

The Class loader concept, one of the cornerstones of the Java virtual machine, describes the behavior of converting a named class into the bits responsible for implementing that class. Because class loaders exist, the Java run time does not need to know anything about files and file systems when running Java programs.

Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. It is somewhat special because the virtual machine assumes that it has access to a repository of trusted classes which can be run by the VM without verification.

When a new JVM instance is started , the bootstrap class loader is responsible for loading key java classes like java.lang.Object and other runtime code into memory. The runtime classes are packaged inside jre/lib/rt.jar file. We cannot find the details of the bootstrap class loader in the java language specification, since this is a native implementation. For this reason the behavior of the bootstrap class loader will differ across JVMs.

Java can change its class storage model simply by changing the set of functions that implements the class loader.

Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader.

ex : Bootstrap (primordial) Loads JDK internal classes, java.* packages. (as defined in the sun.boot.class.path system property, typically loads rt.jar and i18n.jar) and is the parent in the Class loaders hierarchy.

next comes the Extensions (Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system property – usually lib/ext directory of the JRE) and then System (Loads classes from system classpath (as defined by the java.class.path property, which is set by the CLASSPATH environment variable or –classpath or –cp command line options) ClassLoaders.

Classes loaded by Bootstrap class loader have no visibility into classes loaded by its descendants (ie Extensions and Systems class loaders).

The classes loaded by system class loader have visibility into classes loaded by its parents (ie Extensions and Bootstrap class loaders).

If there were any sibling class loaders they cannot see classes loaded by each other. They can only see the classes loaded by their parent class loader. For example Sibling1 class loader cannot see classes loaded by
Sibling2 class loader

Both Sibling1 and Sibling2 class loaders have visibilty into classes loaded by their parent class loaders (eg: System, Extensions, and Bootstrap)


Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true


Note : Two objects loaded by different class loaders are never equal even if they carry the same values, which mean a class is uniquely identified in the context of the associated class loader. This applies to singletons too, where each class loader will have its own singleton.

At its simplest, a class loader creates a flat name space of class bodies that are referenced by a string name. The method definition is:

Class r = loadClass(String className, boolean resolveIt);

The variable className contains a string that is understood by the class loader and is used to uniquely identify a class implementation. The variable resolveIt is a flag to tell the class loader that classes referenced by this class name should be resolved (that is, any referenced class should be loaded as well).

We can build our own ClassLoader by being a subclass of java.lang.ClassLoader. The only abstract method that must be implemented is loadClass().

Static Class Loading :

Classes are statically loaded with Java’s 'new' operator.


class MyClass {
public static void main(String args[]) {
Car c = new Car();
}
}



A NoClassDefFoundException is thrown if a class is referenced with Java’s 'new' operator (i.e. static loading) but the runtime system cannot find the referenced class.

Dynamic class loading:

Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time.

we can load classes dynamically by...


Class.forName (String className); //static method which returns a Class


The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime conditions. Once the class is dynamically loaded the following method returns an instance of the loaded class. It’s just like creating a class object with no arguments.



class.newInstance (); //A non-static method, which creates an instance of a class (i.e. creates an object).
Jeep myJeep = null ;

//myClassName should be read from a properties file or Constants interface.

//stay away from hard coding values in your program.
String myClassName = "au.com.Jeep" ;
Class vehicleClass = Class.forName(myClassName) ;
myJeep = (Jeep) vehicleClass.newInstance();
myJeep.setFuelCapacity(50);


A ClassNotFoundException is thrown when an application tries to load in a class through its string name using the following methods but no definition for the class with the specified name could be found:
1. The forName(..) method in class - Class.
2. The findSystemClass(..) method in class - ClassLoader.
3. The loadClass(..) method in class - ClassLoader.

The Java virtual machine has hooks in it to allow a user-defined class loader to be used in place of the primordial one. Furthermore, since the user class loader gets first crack at the class name, the user is able to implement any number of interesting class repositories, not the least of which is HTTP servers -- which got Java off the ground in the first place.

There is a cost, however, because the class loader is so powerful (for example, it can replace java.lang.Object with its own version), Java classes like applets are not allowed to instantiate their own loaders. (This is enforced by the class loader, by the way.) This column will not be useful if you are trying to do this stuff with an applet, only with an application running from the trusted class repository (such as local files).

Hope it will be useful...