Tuesday, August 5, 2008

Netscape's JavaScript is related to Java

JavaScript and Java seem to have little in common other than their names. JavaScript is a scripting language that can be used within an HTML page. It is similar in concept (though clearly not in capabilities) to scripting languages like Perl and the shell languages of the Korn and Bourne shells. JavaScript commands appear as text within the HTML, as in this example from Netscape's site:


function addChar(input, character)
{
// auto-push the stack if the last value was computed
if(computed) {
pushStack(input.form)
computed = false
}

// make sure input.value is a string
if(input.value == null || input.value == "0")
input.value = character
else
input.value += character
}

Java code does not appear as part of the HTML. Instead, the HTML contains a link to the compiled code module:



The syntax of Java and JavaScript are different as well. Java is more C++-like, where JavaScript looks more like ksh. (Notice the function keyword and the lack of semicolons at the end of each JavaScript statement.) It is even more class-oriented than C++: every Java function must be a method of some class. There are no global variables or functions in Java.


public class Clock extends java.applet.Applet implements Runnable {

Thread clockThread;

public void start() {
if (clockThread == null) {
clockThread = new Thread(this, "Clock");
clockThread.start();
}
}


It's possible that Netscape took a long, hard look at Java as they began work on LiveScript, which became JavaScript. But from a programmer's perspective, Java and JavaScript are about as similar as C and the C Shell.

Here's the square root example as embedded JavaScript. You'll need Netscape 2.0 or later to see it:


sqrt(1) = 1
sqrt(2) = 1.4142135623730951
sqrt(3) = 1.7320508075688772
sqrt(4) = 2
sqrt(5) = 2.23606797749979
sqrt(6) = 2.449489742783178
sqrt(7) = 2.6457513110645907
sqrt(8) = 2.8284271247461903
sqrt(9) = 3
sqrt(10) = 3.1622776601683795

View the document source to see the JavaScript code that built this table.

Here's an example that uses JavaScript to access one of several search engines. There's a hidden form for each search. The form on the page invokes a JavaScript function which sets up the appropriate hidden form and submits the request. This technique will work with search engines that expect Get or Post requests:

To do the same task in Java would require a lot more code. A Java applet would have to set up the user interface, as well as format and submit the various types of requests.

In general, JavaScript is preferable when you want to manipulate the contents or behavior of an HTML page in simple ways. More dynamic or sophisticated behavior is better done within Java applets.

0 comments: