Este capitulo presenta JavaScript y analiza algunos de sus conceptos fundamentales.
Qué es JavaScript?
JavaScript es un lenguaje de scripting multiplataforma, orientado a objetos. JavaScript es un pequeño y liviano lenguaje; no es útil como lenguaje independiente, pero esta diseñado para ser facilmente embebido en otros productos y aplicaciones, como ser web browsers. Dentro de un entorno de desarrollo, JavaScript puede ser conectado a los objetos de este entorno y proveer un control programatico sobre ellos.
El nucleo de JavaScript contiene un set de objetos predefinidos, como ser Array, Date, y Math, y un set de elementos del lenguaje como ser operadores, estructuras de control y declaraciones. El nucleo de JavaScript puede ser complementado para una variedad de propositos utilizando objetos adicionales; por ejemplo:
- Client-side JavaScript extends the core language by supplying objects to control a browser (Navigator or another web browser) and its Document Object Model (DOM). For example, client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation.
- JavaScript del lado del cliente extiende el nucleo del lenguaje proporcionando objetos para controlar el browser (Navigator u otros Browsers) y su Modelo de Documentos Orientados a Objeto (DOM). Por ejemplo, las extenciones del lado del cliente permiten a una aplicación colocar elementos en un formulario HTML y responder a los eventos del usuario como clicks del mouse, ingresos en formularios, y navegación en la página.
- Server-side JavaScript extends the core language by supplying objects relevant to running JavaScript on a server. For example, server-side extensions allow an application to communicate with a relational database, provide continuity of information from one invocation to another of the application, or perform file manipulations on a server.
- Javascript del lado del servidor extiende el nucleo del lenguaje proporcionando objetos relevantes para el servidor. Por ejemplo, las extensiones del lado del servidor permiten a las aplicaciones comunicarse con una base de datos relacional, proveyendo un flujo constante de informacion, o realizar movimientos de archivos en el servidor.
A través de LiveConnect, se puede lograr que el código java y el de javascript se comuniquen entre sí. Desde JavaScript, se puede instanciar objetos de java y acceder a sus metodos publicos y campos. Desde Java, podes acceder a Objetos de Javascript, propiedades y metodos.
Netscape invento JavaScript, y JavaScript fue usado por primera vez en navegadores Netscape.
JavaScript y Java
Javascript y Java son similares en algunos puntos, pero fundamentalmente diferentes en otros. El lenguaje Javascript se parece al de Java pero no tiene el tipado estatico y comprobación de tipos fuerte. Javascript tiene sintaxis, convenciones de nombres y controles basicos de flujo parecidos a los de Java, por eso es que se le cambio el nombre de Livescript a javascript.
En contraste con el sistema de clases construidas por declaraciones en tiempo de compilacion de Java, Javascript soporta un sistema en tiempo de ejecucion basado en un pequeño numero de tipos de datos que representan valores numericos, booleanos, y cadenas. Javascript tiene un modelo de objetos basado en prototipos en lugar del mas comun modelo de objetos basado en clases. El modelo basado en prototipos provee herencia dinamica; esto es, lo que se hereda puede variar para objetos individuales. Javascript tambien soporta funciones sin ningun requerimiento declarativo especial. Las funciones pueden ser propiedades de objetos, ejecutandose como metodos debilmente tipados.
In contrast to Java's compile-time system of classes built by declarations, JavaScript supports a runtime system based on a small number of data types representing numeric, Boolean, and string values. JavaScript has a prototype-based object model instead of the more common class-based object model. The prototype-based model provides dynamic inheritance; that is, what is inherited can vary for individual objects. JavaScript also supports functions without any special declarative requirements. Functions can be properties of objects, executing as loosely typed methods.
JavaScript is a very free-form language compared to Java. You do not have to declare all variables, classes, and methods. You do not have to be concerned with whether methods are public, private, or protected, and you do not have to implement interfaces. Variables, parameters, and function return types are not explicitly typed.
Java is a class-based programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes. Java's class-based model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript programming.
In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages such as HyperTalk and dBASE. These scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation.
JavaScript | Java |
---|---|
Object-oriented. No distinction between types of objects. Inheritance is through the prototype mechanism, and properties and methods can be added to any object dynamically. | Class-based. Objects are divided into classes and instances with all inheritance through the class hierarchy. Classes and instances cannot have properties or methods added dynamically. |
Variable data types are not declared (dynamic typing). | Variable data types must be declared (static typing). |
Cannot automatically write to hard disk. | Cannot automatically write to hard disk. |
For more information on the differences between JavaScript and Java, see the chapter Details of the Object Model.
JavaScript and the ECMAScript Specification
Netscape invented JavaScript, and JavaScript was first used in Netscape browsers. However, Netscape is working with Ecma International — the European association for standardizing information and communication systems (ECMA was formerly an acronym for the European Computer Manufacturers Association) to deliver a standardized, international programming language based on core JavaScript. This standardized version of JavaScript, called ECMAScript, behaves the same way in all applications that support the standard. Companies can use the open standard language to develop their implementation of JavaScript. The ECMAScript standard is documented in the ECMA-262 specification.
The ECMA-262 standard is also approved by the ISO (International Organization for Standardization) as ISO-16262. You can find a PDF version of ECMA-262 (outdated version) at the Mozilla website. You can also find the specification on the Ecma International website. The ECMAScript specification does not describe the Document Object Model (DOM), which is standardized by the World Wide Web Consortium (W3C). The DOM defines the way in which HTML document objects are exposed to your script.
Relationship between JavaScript Versions and ECMAScript Editions
Netscape worked closely with Ecma International to produce the ECMAScript Specification (ECMA-262). The following table describes the relationship between JavaScript versions and ECMAScript editions.
JavaScript version | Relationship to ECMAScript edition |
---|---|
JavaScript 1.1 | ECMA-262, Edition 1 is based on JavaScript 1.1. |
JavaScript 1.2 | ECMA-262 was not complete when JavaScript 1.2 was released. JavaScript 1.2 is not fully compatible with ECMA-262, Edition 1, for the following reasons:
|
JavaScript 1.3 | JavaScript 1.3 is fully compatible with ECMA-262, Edition 1. JavaScript 1.3 resolved the inconsistencies that JavaScript 1.2 had with ECMA-262, while keeping all the additional features of JavaScript 1.2 except == and != , which were changed to conform with ECMA-262. |
JavaScript 1.4 | JavaScript 1.4 is fully compatible with ECMA-262, Edition 1. The third version of the ECMAScript specification was not finalized when JavaScript 1.4 was released. |
JavaScript 1.5 | JavaScript 1.5 is fully compatible with ECMA-262, Edition 3. |
The JavaScript Reference indicates which features of the language are ECMAScript-compliant.
JavaScript will always include features that are not part of the ECMAScript Specification; JavaScript is compatible with ECMAScript, while providing additional features.
JavaScript Documentation versus the ECMAScript Specification
The ECMAScript specification is a set of requirements for implementing ECMAScript; it is useful if you want to determine whether a JavaScript feature is supported in other ECMAScript implementations. If you plan to write JavaScript code that uses only features supported by ECMAScript, then you may need to review the ECMAScript specification.
The ECMAScript document is not intended to help script programmers; use the JavaScript documentation for information on writing scripts.
JavaScript and ECMAScript Terminology
The ECMAScript specification uses terminology and syntax that may be unfamiliar to a JavaScript programmer. Although the description of the language may differ in ECMAScript, the language itself remains the same. JavaScript supports all functionality outlined in the ECMAScript specification.
The JavaScript documentation describes aspects of the language that are appropriate for a JavaScript programmer. For example:
- The Global Object is not discussed in the JavaScript documentation because you do not use it directly. The methods and properties of the Global Object, which you do use, are discussed in the JavaScript documentation but are called top-level functions and properties.
- The no parameter (zero-argument) constructor with the
Number
andString
objects is not discussed in the JavaScript documentation, because what is generated is of little use. ANumber
constructor without an argument returns +0, and aString
constructor without an argument returns "" (an empty string).