Please Enter Your Search Term Below:
 Websearch   Directory   Dictionary   FactBook 
  Wikipedia: JavaScript

Wikipedia: JavaScript
JavaScript
From Wikipedia, the free encyclopedia.

JavaScript is an object-oriented scripting language originally developed by Netscape Communications under the name LiveScript but then renamed to "JavaScript" and given a syntax closer to that of Sun Microsystems' Java language. JavaScript was later standardized by ECMA under the name ECMAScript. The current standard (as of December 1999) is ECMA-262 Edition 3, and corresponds to JavaScript 1.5. Microsoft calls their version JScript.

Java and JavaScript

The change of name from LiveScript to JavaScript happened at roughly the same time Netscape was including support for Java technology in its Netscape Navigator browser. Consequently, the change proved a source of much confusion. There is no real relation between Java and JavaScript; their only similarities are some syntax and the fact that both languages are used extensively on the World Wide Web.

Usage

JavaScript is an object-oriented scripting language that 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 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.

JavaScript/ECMAScript is implemented by:

Environment

The Internet media type for JavaScript source code is text/javascript, but application/x-javascript is an unofficial MIME type which is also used.

To put JavaScript code in an HTML page, it must be preceded with

 <script type="text/javascript">
and followed with
 </script>

For very old browsers, instead use
 <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 a CDATA sections, by preceding with
 <script type="text/javascript">
 //<![CDATA[
and following it 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 webbrowser quirks. 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 like Opera and Safari use an ECMAScript implementation with additional nonstandard properties.

JavaScript and JScript contain several properties which are not part of the official ECMAScript standard, and also miss several properties. As such, they are in points incompatible, which requires script authors to work around these bugs.

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.

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.

Data structures

The primary data structure is an associative array similar to hashes in the Perl programming language, or dictionaries in Python, PostScript and Smalltalk.

Elements may be accessed by numbers or associative names (if defined with them). Thus the following expressions may all be equivalent:

  myArray[1], 
  myArray.north, 
  myArray["north"].

Declaration of an array:
 myArray = new Array(365);

Arrays are implemented so that only the elements defined use memory; they are "sparse arrays". If I only set myArray[10] = 'someThing' and myArray[57] = 'somethingOther' I have only used space for these two elements.

Objects

JavaScript has several kinds of built in objects, namely Object, Array, String, Number, Boolean, Function, Date and Math. Other 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. One can add additional properties or methods to individual objects after they have been created. To do this for all instances of a certain object type one can use the prototype statement.

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()

Control structures

If ... else

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

While loop

  while (condition) {
     statements
  }

Do ... while

  do {
     statements
  } while (condition);

For loop

  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

  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) {
           solution = segmentA - segmentB;
           }
        else {
           solution = segmentB - segmentA;
           }
        }
     return(solution);
     }

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:

  • Alert dialog box
  • Confirm dialog box
  • Prompt dialog box
  • Status bar
  • Console

Events

Text elements may be the source of various events which can cause an action if a EMCAScript 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/

Error handling

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
  }

Offspring

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

A similar programming language like JavaScript is used in Macromedia Flash. There it is called ActionScript.

External links


  

From Wikipedia, the free encyclopedia. 
Modified by Geona