Jump to content

JavaScript

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by 200.49.224.3 (talk) at 00:59, 25 November 2004 (Usage: comma added). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

JavaScript is an object-oriented scripting language commonly used in websites. It was originally developed by Brendan Eich of Netscape Communications under the name Mocha and then LiveScript but then renamed to "JavaScript" and given a syntax closer to that of Sun MicrosystemsJava language. JavaScript was first standardized in 1997–1999 by ECMA under the name ECMAScript. The standard (as of December 1999) is ECMA-262 Edition 3, and corresponds to JavaScript 1.5. This is also now an ISO standard.

Java, JavaScript, and JScript

The change of name from LiveScript to JavaScript happened at roughly the time that Netscape was including support for Java technology in its Netscape Navigator browser. The choice of name proved to be a source of much confusion. There is no real relation between Java and JavaScript; their similarities are mostly in syntax (both derived from C); their semantics are quite different, notably their object models are unrelated and largely incompatible.

Due to the de facto success of JavaScript as a web page enhancement language, Microsoft had little choice but to develop a compatible language; this is known as JScript. The need for common specifications for that language was the basis of the ECMA 262 standard for ECMAScript (see external links below), three editions of which have been published since the work started in November 1996 (and which in turn set the stage for the standardization of C# a few years later).

Usage

JavaScript is an object-based scripting language with a syntax loosely based on C. Like C, it has the concept of reserved keywords, which (being executed from source) means it is almost impossible to extend the language without breakage.

Also like C, the language has no input or output constructs of its own; where C relies on standard I/O libraries, a JavaScript interpreter relies on a host program into which it is trivially (or more complexly) embedded. There are many such host programs, of which Web technologies are the most well known examples. These are examined first.

JavaScript embedded in a Web browser connects through interfaces called Document Object Models (DOMs) to applications, especially to the server side (web servers) and the client side web browser of internet applications. Many web sites use client-side JavaScript technology to create powerful dynamic web applications. It may use Unicode and can evaluate regular expressions (introduced in version 1.2 in Netscape Navigator 4 and Internet Explorer 4). JavaScript expressions contained in a string can be evaluated using the eval function.

One major use of Web-based JavaScript is to write little functions that are embedded in HTML pages and interact with the DOM of the browser to perform certain tasks not possible in static HTML alone, such as opening a new window, checking input values, changing images as the mouse cursor moves over, etc. Unfortunately, the DOMs of browsers are not standardized, different browsers expose different objects or methods to the script, and it is therefore often necessary to write different variants of a JavaScript function for the various browsers.

Outside of the Web, JavaScript interpreters are embedded in a number of tools. Adobe Acrobat and Adobe Reader support JavaScript in PDF files. The Mozilla platform, which underlies several common Web browsers, uses JavaScript to implement the user interface and transaction logic of its various products. JavaScript interpreters are also embedded in proprietary applications that lack scriptable interfaces. Finally, Microsoft's WSH technology supports JavaScript (via JScript) as an operating system scripting language.

Each of these applications provides its own object model which provides access to the host environment, with the core JavaScript language remaining mostly the same in each application.

There are a number of different implementations of the core JavaScript language, including:

Environment

The Internet media type for JavaScript source code is application/x-javascript, but the unregistered text/javascript is more commonly used.

To embed JavaScript code in an HTML document, it must be preceded with:

 <script type="text/javascript">

and followed with:

 </script>

Older browsers typically require JavaScript to begin with:

 <script language="JavaScript" type="text/javascript">
 <!--

and end with:

 // -->
 </script>

The <!-- ... --> comment markup is required in order to ensure that the code is not rendered as text by very old browsers which do not recognize the <script> tag in HTML documents, and the LANGUAGE attribute is a deprecated HTML attribute which may be required for old browsers. However, <script> tags in XHTML/XML documents will not work if commented out, as conformant XHTML/XML parsers ignore comments and also may encounter problems with --, < and > signs in scripts (for example, the integer decrement operator and the comparison operators). XHTML documents should therefore have scripts included as XML CDATA sections, by preceding them with

 <script type="text/javascript">
 //<![CDATA[

and following them with

 //]]>
 </script>

('//' At the start of a line marks a Javascript comment, which prevents the '<![CDATA[' and ']]>' from being parsed by the script.)

HTML elements[1] may contain intrinsic events to which you can associate a script handler. To write valid HTML 4.01, the web server should return a 'Content-Script-Type' with value 'text/javascript'. If the web server cannot be so configured, the website author can optionally insert the following declaration for the default scripting language in the header section of the document.

  <meta http-equiv="Content-Script-Type" content="text/javascript" />

Incompatibilities

Javascript, like HTML, is often not compliant to standards, instead being built to work with specific web browsers. The current ECMAScript standard should be the base for all Javascript implementations in theory, but in practice the Netscape (and Mozilla) browsers use JavaScript, Microsoft Internet Explorer uses JScript, and other browsers such as Opera and Safari use other ECMAScript implementations, often with additional nonstandard properties to allow compatibility with JavaScript and JScript.

JavaScript and JScript contain several properties which are not part of the official ECMAScript standard, and may also miss several properties. As such, they are in points incompatible, which requires script authors to work around these bugs. JavaScript is more standards-compliant than Microsoft's JScript, which means that a script file written according to the ECMA standards will work for most browsers, except those based on Internet Explorer.

This also means every browser may treat the same script differently, and what works for one browser may fail in another browser, or even in a different version of the same browser. Like with HTML, it is thus advisable to write standards-compliant code.

MSIE's VBScript is not JavaScript, and it is incompatible with the ECMA standard.

Combating Incompatibilities

There are two primary techniques for handling incompatibilities: browser sniffing and object detection. When there were only two browsers that had scripting capabilities (Netscape and Internet Explorer), browser sniffing was the most popular technique. By testing a number of "client" properties, that returned information on computer platform, browser, and versions, it was possible for a scripter's code to discern exactly which browser the code was being executed in. Later, the techniques for sniffing became more difficult to implement, as Internet Explorer began to "spoof" its client information, that is, to provide browser information that was increasingly inaccurate, (the reasons why Microsoft did this are often disputed). Later still, browser sniffing became something of a difficult art form, as other scriptable browsers came onto the market, each with its own platform, client, and version information.

Object detection relies on testing for the existence of a property of an object.

function set_image_source( imageName, imageURL )
{
    if ( document.images ) // a test to discern if the 'document' object has a property called 'images'
    {
        document.images[ imageName ].src = imageURL; // only executed if there is an 'images' array
    }
}

A more complex example relies on using joined boolean tests:

if ( document.body && document.body.style )

In the above, the statement "document.body.style" would ordinarily cause an error in a browser that does not have a "document.body" property, but using the boolean operator "&&" ensures that "document.body.style" is never called if "document.body" doesn't exist. This technique is called Lazy evaluation.

Today, a combination of browser sniffing, object detection, and reliance on standards such as the ECMAScript specification and Cascading Style Sheets are all used to varying degrees to try to ensure that a user never sees a JavaScript error message.

Language elements

Variables

Variables are generally dynamically typed. Variables are defined by either just assigning them a value or by using the var statement. Variables declared outside of any function are in "global" scope, visible in the entire web page; variables declared inside a function are local to that function. To pass variables from one page to another, a developer can set a cookie or use a hidden frame or window in the background to store them.

Objects

Everything in JavaScript is either a primitive value or an object. Objects are entities that have an identity (they are only equal to themselves) and that map property names to values. That is, an object is an associative array similar to hashes in the Perl programming language, or dictionaries in Python, PostScript and Smalltalk.

JavaScript has several kinds of built in objects, namely Array, Boolean, Date, Function, Math, Number, Object, RegExp and String. Other objects are "host objects", defined not by the language but by the runtime environment. In a browser, typical host objects belong to the DOM (window, form, links etc.).

By defining a constructor function it is possible to define objects. JavaScript is a prototype based object-oriented language. This means that inheritance is between objects, not between classes (Javascript has no classes). Objects inherit properties from their prototypes.

One can add additional properties or methods to individual objects after they have been created. To do this for all instances created by a single constructor function, one can use the prototype property of the constructor to access the prototype object.

Example: Creating an object

// constructor function
function MyObject(attributeA, attributeB) {
  this.attributeA = attributeA
  this.attributeB = attributeB
}

// create an Object
obj = new MyObject('red', 1000)

// access an attribute of obj
alert(obj.attributeA)

// access an attribute with the associative array notation
alert(obj["attributeA"])

Object hierarchy can be emulated in JavaScript. For example:

function Base()
{
  this.Override = _Override;
  this.BaseFunction = _BaseFunction;
  function _Override()
  {
    alert("Base::Override()");
  }
  function _BaseFunction()
  {
    alert("Base::BaseFunction()");
  }
}

function Derive()
{
   this.Override = _Override;
   function _Override()
   {
     alert("Derive::Override()");
   }
}
Derive.prototype = new Base();

d = new Derive();
d.Override();
d.BaseFunction();

will result in the display:

Derive::Override()
Base::BaseFunction()

Data structures

A typical data structure is the Array, which is a map from integers to values. In Javascript, all objects can map from integers to values, but Arrays are a special type of objects that has extra behavior and methods specializing in integer indices (e.g., join, slice, and push).

Arrays have a length property that is guaranteed to always be larger than the largest integer index used in the array. It is automatically updated if one creates a property with an even larger index. Writing a smaller number to the length property will remove larger indices. This length property is the only special feature of Arrays, that distinguishes it from other objects.

Elements of Arrays may be accessed using normal object property access notation:

  myArray[1]
  myArray["1"]

These two are equivalent. Its not possible to use the "dot"-notation or strings with alternative representations of the number:

  myArray.1 (syntax error)
  myArray["01"] (not the same as myArray[1])

Declaration of an array can use either an Array literal or the Array constructor:

 myArray = [0,1,,,4,5]; (array with length 6 and 4 elements)
 myArray = new Array(0,1,2,3,4,5); (array with length 6 and 6 elements)
 myArray = new Array(365); (an empty array with length 365)

Arrays are implemented so that only the elements defined use memory; they are "sparse arrays". Setting myArray[10] = 'someThing' and myArray[57] = 'somethingOther' only uses space for these two elements, just like any other object. The length of the array will still be reported as 58.

Control structures

If ... else

  if (condition) {
     statements
  }
  [else {
     statemesnts
  }]
  while (condition) {
     statements
  }

Do ... while

  do {
     statements
  } while (condition);
  for ([initial-expression]; [condition]; [increment-expression]) {
     statements
  }

For ... in loop

This loop goes through all properties of an object (or elements of an array).

  for (variable in object) {
     statement
  }
  switch (expression) {
     case label1 :
        statements;
        break;
     case label2 :
        statements;
        break;
     default :
        statements;
  }

Functions

A function is a block with a (possibly empty) argument list that is normally given a name. A function may give back a return value.

  function(arg1, arg2, arg3) {
     statements;
     return expression;
  }

Example: Euclid's original algorithm of finding the greatest common divisor. (This is a geometrical solution which subtracts the longer segment from the shorter):

  function gcd(segmentA, segmentB)
  {
     while(segmentA!=segmentB)
        if(segmentA>segmentB)
           segmentA -= segmentB;
        else
           segmentB -= segmentA;
     return(segmentA);
  }

The number of arguments given when calling a function must not necessarily accord to the number of arguments in the function definition. Within the function the arguments may as well be accessed through the arguments array.

Every function is an instance of Function, a type of base object. Functions can be created and assigned like any other objects:

   var myFunc1 = new Function("alert('Hello')");
   var myFunc2 = myFunc1;
   myFunc2();

results in the display:

   Hello

User interaction

Most interaction with the user is done by using HTML forms which can be accessed through the HTML DOM. However there are as well some very simple means of communicating with the user:

Events

Text elements may be the source of various events which can cause an action if a ECMAScript event handler is registered. In HTML these event handler functions are often defined as anonymous functions directly within the HTML tag.

List of events

  • onAbort
  • onBlur1
  • onChange
  • onClick
  • onDblClick
  • onDragDrop
  • onError
  • onFocus2
  • onKeyDown
  • onKeyPress
  • onKeyUp
  • onLoad
  • onMouseDown
  • onMouseMove
  • onMouseOut
  • onMouseOver
  • onMouseUp
  • onMove
  • onReset
  • onResize
  • onSelect
  • onSubmit
  • onUnload

1 Blur is when the object is deselected or something else is selected instead.
2 Focus is when the object is selected, usually in a form.

See also http://tech.irt.org/articles/js058/

Newer versions of JavaScript (as used in Internet Explorer 5 and Netscape 6) include a try ... catch error handling statement.

The try ... catch ... finally statement catches exceptions resulting from an error or a throw statement. Its syntax is as follows:

  try {
     // Statements in which exceptions might be thrown
  } catch(error) {
     // Statements that execute in the event of an exception
  } finally {
     // Statements that execute afterward either way
  }

Initially, the statements within the try block execute. If an exception is thrown, the script's control flow immediately transfers to the statements in the catch block, with the exception available as the error argument. Otherwise the catch block is skipped. Once the catch block finishes, or the try block finishes with no exceptions thrown, the statements in the finally block execute. This figure summarizes the operation of a try...catch...finally statement:

Here's a script that shows try ... catch ... finally in action step by step.

  try {
     statements
  }

  catch (err) {
     // handle error
  }
  finally {
     statements
  } 

The finally part may be omitted:

  try {
     statements
  }
  catch (err) {
     // handle error
  }

Common Uses in Web Browsers

JavaScript may be used for all aspects of client-side scripting of a web browser, however, some uses have become more ubiquitous than others. Common examples include image replacement, the creation of pop-up windows, and the validating of form content.

In most modern browsers, the following snippet of XHTML source code shows one way in which an image can be made to swap out with another image when a user moves their cursor over it, (often called a rollover or mouse over effect). However similar behaviour can be achieved using only pure CSS.

<img src = "normal.png"
     onclick     = "window.location='http://en.wikipedia.org/'"
     onmouseover = "this.src='rollover.png'"
     onmouseout  = "this.src='normal.png'" />

Offspring

A novel example of the use of JavaScript are Bookmarklets, small sections of code within web browser Bookmarks or Favorites.

The programming language used in Macromedia Flash (called ActionScript) bears a strong resemblance to JavaScript due to their shared relationship with ECMAScript. ActionScript has nearly the same syntax as JavaScript, but the object model is dramatically different.

JavaScript for OSA, (JavaScript OSA, or JSOSA), is a Macintosh scripting language based on the Mozilla 1.5 JavaScript implementation. It is a freeware component made available by Late Night Software. Interaction with the operating system and with third-party applications is scripted via a MacOS object. Otherwise, the language is virtually identical to the core Mozilla implementation. It was offered as an alternative to the more commonly used AppleScript language.

See also

References

  • Nigel McFarlane: Rapid Application Development with Mozilla, Prentice Hall Professional Technical References, ISBN 0131423436
  • David Flanagan, Paula Ferguson: JavaScript: The Definitive Guide, O'Reilly & Associates, ISBN 0596000480
  • Danny Goodman, Scott Markel: JavaScript and DHTML Cookbook, O'Reilly & Associates, ISBN 0596004672
  • Danny Goodman, Brendan Eich: JavaScript Bible, Wiley, John & Sons, ISBN 0764533428
  • Andrew H. Watt, Jinjer L. Simon, Jonathan Watt: Teach Yourself JavaScript in 21 Days, Pearson Education, ISBN 0672322978
  • Thomas A. Powell, Fritz Schneider: JavaScript: The Complete Reference, McGraw-Hill Companies, ISBN 0072191279
  • Scott Duffy: How to do Everything with JavaScript, Osborne, ISBN 0072228873
  • Andy Harris, Andrew Harris: Javascript Programming, Premier Press, ISBN 0761534105
  • Joe Burns, Andree S. Growney, Andree Growney: JavaScript Goodies, Pearson Education, ISBN 0789726122
  • Gary B. Shelly, Thomas J. Cashman, William J. Dorin, Jeffrey Quasney: Javascript: Complete Concepts and Techniques, Course Technology, ISBN 0789562332
  • Nick Heinle, Richard Koman: Designing with Javascript, O'Reilly & Associates, ISBN 1565923006
  • Sham Bhangal, Tomasz Jankowski: Foundation Web Design: Essential HTML, Javascript, CSS, PhotoShop, Fireworks, and Flash, APress L. P., ISBN 1590591526

Template:Major programming languages small