Обзор JavaScript

  • Revision slug: JavaScript/Guide/ru_JavaScript_Overview
  • Revision title: Обзор JavaScript
  • Revision id: 443825
  • Created:
  • Creator: smfd
  • Is current revision? Нет
  • комментировать

Revision Content

Эта глава является введением в JavaScript и описывает некоторые из базовых понятий.

Что такое JavaScript?

JavaScript это кросс-платформенный, объектно-ориентированный, скриптовый язык. JavaScript - это маленький и легковесный язык; он спроектирован не для создания законченных, полноценных приложений,  а для легкого встраивания в другие продукты и приложения, например, в веб браузеры. Внутри основного приложения, JavaScript может соединяться с объектами этого приложения и осуществлять программный контроль над ними.

Ядро JavaScript содержит набор базовых объектов, например Array, Date и Math, и набор элементов языка: операторов, управляющих структур, и выражений. Ядро JavaScript может быть расширено для различных целей с помощью дополнений, например:

  • Client-side JavaScript расширяет ядро ​​языка, предоставляя объекты управления браузером (Navigator или другой веб-браузер) и его Document Object Model (DOM). Например, клиентские расширения позволяют приложению размещать элементы в HTML-форме и реагировать на пользовательские события, такие как щелчок мыши, ввод данных в форму и навигация по страницам.
  • Server-side JavaScript расширяет ядро языка предоставляя объекты для запуска JavaScript на сервере. Например, server-side расширения позволяют приложению соединяться с реляционной базой данных, обеспечивать непрерывность информации между вызовами приложения, или выполнять операции над фалами на сервере.

Используя функции JavaScript LiveConnect, Вы можете позволить коду на Java и JavaScript общаться между собой. Вы можете создать экземпляр объекта Java из JavaScript и получить доступ к его публичным методам и свойствам. Из Java, Вы можете получить доступ к объектам, свойствам и методам JavaScript.

JavaScript был создан в Netscape; впервые JavaScript был использован в браузерах Netscape.

JavaScript and Java

JavaScript and Java are similar in some ways but fundamentally different in some others. The JavaScript language resembles Java but does not have Java's static typing and strong type checking. JavaScript follows most Java expression syntax, naming conventions and basic control-flow constructs which was the reason why it was renamed from LiveScript to JavaScript.

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.

Table 1.1 JavaScript compared to Java
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.

Table 1.2 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:
  • Netscape developed additional features in JavaScript 1.2 that were not considered for ECMA-262.
  • ECMA-262 adds two new features: internationalization using Unicode, and uniform behavior across all platforms. Several features of JavaScript 1.2, such as the Date object, were platform-dependent and used platform-specific behavior.

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.
Note: ECMA-262, Edition 2 consisted of minor editorial changes and bug fixes to the Edition 1 specification. The  current release by the TC39 working group of Ecma International is ECMAScript Edition 5.1

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 and String objects is not discussed in the JavaScript documentation, because what is generated is of little use. A Number constructor without an argument returns +0, and a String constructor without an argument returns "" (an empty string).

{{ autoPreviousNext("JSGChapters") }}

Revision Source

<p>Эта глава является введением в JavaScript и описывает некоторые из базовых понятий.</p>
<h3 id="What_is_JavaScript.3F" name="What_is_JavaScript.3F">Что такое JavaScript?</h3>
<p>JavaScript это кросс-платформенный, объектно-ориентированный, скриптовый язык. JavaScript - это маленький и легковесный язык; он спроектирован не для создания законченных, полноценных приложений,&nbsp; а для легкого встраивания в другие продукты и приложения, например, в веб браузеры. Внутри основного приложения, JavaScript может соединяться с объектами этого приложения и осуществлять программный контроль над ними.</p>
<p>Ядро JavaScript содержит набор базовых объектов, например Array, Date и Math, и набор элементов языка: операторов, управляющих структур, и выражений. Ядро JavaScript может быть расширено для различных целей с помощью дополнений, например:</p>
<ul>
  <li><em>Client-side JavaScript</em>&nbsp;расширяет ядро ​​языка, предоставляя объекты управления браузером (Navigator или другой веб-браузер) и его Document Object Model (DOM). Например, клиентские расширения позволяют приложению размещать элементы в HTML-форме и реагировать на пользовательские события, такие как щелчок мыши, ввод данных в форму и навигация по страницам.</li>
  <li><em>Server-side JavaScript</em> расширяет ядро языка предоставляя объекты для запуска JavaScript на сервере. Например, server-side расширения позволяют приложению соединяться с реляционной базой данных, обеспечивать непрерывность информации между вызовами приложения, или выполнять операции над фалами на сервере.</li>
</ul>
<p>Используя функции JavaScript LiveConnect, Вы можете позволить коду на Java и JavaScript общаться между собой. Вы можете создать экземпляр объекта Java из JavaScript и получить доступ к его публичным методам и свойствам. Из Java, Вы можете получить доступ к объектам, свойствам и методам JavaScript.</p>
<p>JavaScript был создан в Netscape;&nbsp;впервые JavaScript&nbsp;был использован в браузерах Netscape.</p>
<h3 id="JavaScript_and_Java" name="JavaScript_and_Java">JavaScript and Java</h3>
<p>JavaScript and Java are similar in some ways but fundamentally different in some others. The JavaScript language resembles Java but does not have Java's static typing and strong type checking. JavaScript follows most Java expression syntax, naming conventions&nbsp;and basic control-flow constructs which was the reason why it was renamed from LiveScript to JavaScript.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<table class="standard-table">
  <caption style="text-align: left">
    Table 1.1 JavaScript compared to Java</caption>
  <thead>
    <tr>
      <th scope="col">JavaScript</th>
      <th scope="col">Java</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>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.</td>
      <td>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.</td>
    </tr>
    <tr>
      <td>Variable data types are not declared (dynamic typing).</td>
      <td>Variable data types must be declared (static typing).</td>
    </tr>
    <tr>
      <td>Cannot automatically write to hard disk.</td>
      <td>Cannot automatically write to hard disk.</td>
    </tr>
  </tbody>
</table>
<p>For more information on the differences between JavaScript and Java, see the chapter <a href="/en/JavaScript/Guide/Details_of_the_Object_Model" title="en/JavaScript/Guide/Details of the Object Model">Details of the Object Model</a>.</p>
<h3 id="JavaScript_and_the_ECMAScript_Specification" name="JavaScript_and_the_ECMAScript_Specification">JavaScript and the ECMAScript Specification</h3>
<p>Netscape invented JavaScript, and JavaScript was first used in Netscape browsers. However, Netscape is working with <a class="external" href="http://www.ecma-international.org/">Ecma International</a>&nbsp;— 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.</p>
<p>The ECMA-262 standard is also approved by the <a class="external" href="http://www.iso.ch/">ISO</a> (International Organization for Standardization) as ISO-16262. You can find a <a class="external" href="http://www-archive.mozilla.org/js/language/E262-3.pdf" title="http://www-archive.mozilla.org/js/language/E262-3.pdf">PDF version of ECMA-262</a> (outdated version) at the Mozilla website. You can also find the specification on <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">the Ecma International website</a>. The ECMAScript specification does not describe the Document Object Model (DOM), which is standardized by the <a class="external" href="http://www.w3.org/">World Wide Web Consortium (W3C)</a>. The DOM defines the way in which HTML document objects are exposed to your script.</p>
<h4 id="Relationship_between_JavaScript_Versions_and_ECMAScript_Editions" name="Relationship_between_JavaScript_Versions_and_ECMAScript_Editions">Relationship between JavaScript Versions and ECMAScript Editions</h4>
<p>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.</p>
<table class="standard-table">
  <caption style="text-align: left">
    Table 1.2 JavaScript versions and ECMAScript editions</caption>
  <thead>
    <tr>
      <th scope="row">JavaScript version</th>
      <th scope="col">Relationship to ECMAScript edition</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>JavaScript 1.1</td>
      <td>ECMA-262, Edition 1 is based on JavaScript 1.1.</td>
    </tr>
    <tr>
      <td>JavaScript 1.2</td>
      <td>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:
        <ul>
          <li>Netscape developed additional features in JavaScript 1.2 that were not considered for ECMA-262.</li>
          <li>ECMA-262 adds two new features: internationalization using Unicode, and uniform behavior across all platforms. Several features of JavaScript 1.2, such as the <code>Date</code> object, were platform-dependent and used platform-specific behavior.</li>
        </ul>
      </td>
    </tr>
    <tr>
      <td>
        <p>JavaScript 1.3</p>
      </td>
      <td>
        <p>JavaScript 1.3 is fully compatible with ECMA-262, Edition 1.</p>
        <p>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&nbsp;!=, which were changed to conform with ECMA-262.</p>
      </td>
    </tr>
    <tr>
      <td>
        <p>JavaScript 1.4</p>
      </td>
      <td>
        <p>JavaScript 1.4 is fully compatible with ECMA-262, Edition 1.</p>
        <p>The third version of the ECMAScript specification was not finalized when JavaScript 1.4 was released.</p>
      </td>
    </tr>
    <tr>
      <td>JavaScript 1.5</td>
      <td>JavaScript 1.5 is fully compatible with ECMA-262, Edition 3.</td>
    </tr>
  </tbody>
</table>
<div class="note">
  <strong>Note</strong>: ECMA-262, Edition 2 consisted of minor editorial changes and bug fixes to the Edition 1 specification. The&nbsp; current release by the TC39 working group of Ecma International is ECMAScript Edition 5.1</div>
<p>The <a href="/en/JavaScript/Reference" title="en/JavaScript/Reference">JavaScript Reference</a> indicates which features of the language are ECMAScript-compliant.</p>
<p>JavaScript will always include features that are not part of the ECMAScript Specification; JavaScript is compatible with ECMAScript, while providing additional features.</p>
<h4 id="JavaScript_Documentation_versus_the_ECMAScript_Specification" name="JavaScript_Documentation_versus_the_ECMAScript_Specification">JavaScript Documentation versus the ECMAScript Specification</h4>
<p>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.</p>
<p>The ECMAScript document is not intended to help script programmers; use the JavaScript documentation for information on writing scripts.</p>
<h4 id="JavaScript_and_ECMAScript_Terminology">JavaScript and ECMAScript Terminology</h4>
<p>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.</p>
<p>The JavaScript documentation describes aspects of the language that are appropriate for a JavaScript programmer. For example:</p>
<ul>
  <li>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.</li>
  <li>The no parameter (zero-argument) constructor with the <code>Number</code> and <code>String</code> objects is not discussed in the JavaScript documentation, because what is generated is of little use. A <code>Number</code> constructor without an argument returns +0, and a <code>String</code> constructor without an argument returns "" (an empty string).</li>
</ul>
<p>{{ autoPreviousNext("JSGChapters") }}</p>
Revert to this revision