JavaScript: розьніца паміж вэрсіямі

Змесціва выдалена Змесціва дададзена
are we idiots? why do i have to wait so long for my global block?
д Рэдагаваньні 79.170.44.156 (гутаркі) скасаваныя да папярэдняй вэрсіі DixonDBot
Радок 1:
'''JavaScript''' (вымаўляецца: ''яваскрыпт/джаваскрыпт'') — [[Аб'ектна-арыентаванае праграмаваньне|аб'ектна-арыентаваная]] [[скрыптовая мова праграмаваньня]], якая часта ўжываецца для напісаньня скрыптоў [[html]]-старонак у [[Інтэрнэт|інтэрнэце]].
{{distinguish|Java (programming language)}}
{{Selfref|For the use of JavaScript on Wikipedia, see [[Wikipedia:JavaScript]].}}
 
== Гісторыя ==
{{infobox programming language
Мова JavaScript была разпрацавана і ўключаная ў браўзэр [[Netscape]] другой вэрсыі (сьнежань [[1995]]) спачатку пад назвай ''Mocha'', затым ''LiveScript'', і нарэшце перайменаваня ў ''JavaScript''. Сувязь паміж мовамі [[Java]] і JavaScript палягае толькі ў назьве, яны маюць падабенствы толькі ў сынтаксыве (як і Java, JavaScript мае сынтакс падобны на сынтакс мовы [[C (мова праграмаваньня)|C]]). Сэмантыка ж у іх даволі розная, асабліва розьняцца іх падыходы да рэалізацыі аб'ектна-арыентаванай парадыгмы.
| name=JavaScript
| paradigm = [[Multi-paradigm]]: [[scripting language|scripting]], [[prototype-based programming|prototype-based]], [[imperative programming|imperative]], [[functional programming|functional]]<ref name="jsfunc">{{cite video |people= [[Douglas Crockford]] |date= |title= Douglas Crockford on Functional JavaScript |url= http://www.blinkx.com/video/douglas-crockford-on-functional-javascript/xscZz8XhfuNQ_aaVuyUB2A |format= flv |medium= Tech talk |publisher=[[blinkx]] |time= 2:49 |quote=[JavaScript] is also coincidentally the world's most popular functional programming language. JavaScript is and has always been, at least since [version] 1.2, a functional programming language.}}</ref>
| year = 1995
| designer = [[Brendan Eich]]
| developer = [[Netscape Communications Corporation]], [[Mozilla Foundation]]
| latest_release_version = 1.8.2<ref>[https://developer.mozilla.org/en/firefox_3.6_for_developers#JavaScript Firefox 3.6 supports JavaScript 1.8.2]</ref>
| latest_release_date = {{release date and age|2009|6|22}}
| latest_preview_version = 1.8.5<ref>{{cite web|url=https://developer.mozilla.org/en/JavaScript/New_in_JavaScript/1.8.5 |title=New in JavaScript 1.8.5 |publisher=mozilla.org |date= |accessdate=August 10, 2010}}</ref>
| latest_preview_date = {{Release date|2010|7|27}}
| typing = [[dynamic typing|dynamic]], [[weak typing|weak]], [[duck typing|duck]]
| implementations = [[KDE's JavaScript engine|KJS]], [[Rhino (JavaScript engine)|Rhino]], [[SpiderMonkey (JavaScript engine)|SpiderMonkey]], [[V8 (JavaScript engine)|V8]], [[WebKit]]
| influenced_by = [[C (programming language)|C]], [[Scheme (programming language)|Scheme]], [[Java (programming language)|Java]], [[Perl]], [[Python (programming language)|Python]], [[Self programming language|Self]]
| influenced = [[JScript]], [[JScript .NET]], [[Objective-J]], TIScript
| license =
| website =
| wikibooks = JavaScript
}}
{{Infobox file format
| name=JavaScript
| icon =
| logo =
| screenshot =
| caption =
| extension = <code>.js</code>
| mime = application/javascript, text/javascript<ref>[http://www.apps.ietf.org/rfc/rfc4329.html RFC 4329]</ref>
| type code =
| uniform type = com.netscape.javascript-​source<ref>{{cite web
| publisher = Apple Inc.
| url = http://developer.apple.com/mac/library/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html
| title = System-Declared Uniform Type Identifiers
| work = Mac OS X Reference Library
| accessdate = 2010-03-05
| lang = en
}}</ref>
| magic =
| owner =
| released =
| latest release version =
| latest release date =
| genre = [[Scripting language]]
| container for =
| contained by =
| extended from =
| extended to =
| standard =
| url =
}}
{{JavaScriptSidebar}}
 
Бачачы посьпех JavaScript, у фірме [[Microsoft]] распрацавалі сваю мову — [[JScript]], якая ўпершыню зьявілася ў трэцяй вэрсыі браўзэра [[Internet Explorer]] (жнівень [[1996]]). Неабходнасьць агульнага стандарту прывяла да зьяўленьня спэцыфікацыі ECMAScript.
'''JavaScript''' is an [[implementation]] of the [[ECMAScript]] language standard and is typically used to enable [[Computer programming|programmatic]] access to computational objects within a host environment. It can be characterized as a [[prototype-based]] [[Object-oriented programming|object-oriented]]<ref name="ECMA-262">{{cite web|url=http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf | title= ECMAScript Language Specification }}</ref> [[scripting language]] that is [[dynamic language|dynamic]], [[weak typing|weakly typed]] and has [[first-class function]]s. It is also considered a [[functional programming]] language<ref name="jsfunc"/> like [[Scheme (programming language)|Scheme]] and [[OCaml]] because it has [[closure (computer science)|closures]] and supports [[higher-order function]]s.<ref>[http://www.crockford.com/javascript/little.html The Little JavaScripter] shows the relationship with Scheme in more detail.</ref>
 
== Ужываньне ==
JavaScript is primarily used in the form of [[client-side JavaScript]], implemented as part of a [[web browser]] in order to provide enhanced [[user interface]]s and dynamic [[website]]s. However, its use in [[Application software|applications]] outside web pages&mdash;for example in [[Portable Document Format|PDF]]-documents, [[site-specific browser]]s and [[desktop widget]]s&mdash;is also significant.
JavaScript часта ўжываецца ў html-старонках для кіраваньнем аб'ектнай мадэльлю дакумэнтаў ([[DOM]]), што дазваляе ствараць ці зьмяняць структуру і выгляд сайтаў. Код JavaScript зьмяшчаецца паміж тэгамі <code><nowiki><script></script></nowiki></code>. Згодна спэцыфікацыі [http://www.w3.org/TR/html4/interact/scripts.html#h-18.2.1 HTML 4.01] у гэты тэг трэба дадаць атрыбут <code>type="text/javascript"</code>, пры гэтым часта ўжываемы атрыбут <code>language="JavaScript"</code> не адпавядае стандарту.
 
Прыклад:
JavaScript uses syntax influenced by that of [[C (programming language)|C]]. JavaScript copies many names and naming conventions from [[Java (programming language)|Java]], but the two languages are otherwise unrelated and have very different semantics. The key design principles within JavaScript are taken from the [[Self (programming language)|Self]] and [[Scheme (programming language)|Scheme]] programming languages.<ref>{{cite web|title=ECMAScript Language Overview|url=http://www.ecmascript.org/es4/spec/overview.pdf|format=PDF|pages=4|date=2007-10-23|accessdate=2009-05-03}}</ref>
Скрыпт, які паказвае мадальнае акенца з надпісам «Hello, World!»:
 
==History==
{{quote box|width = 200px|Anyway I know only one [[programming language]] worse than [[C (programming language)|C]] and that is Javascript. [...] I was convinced that we needed to build-in a programming language, but the developers, [[Tim Berners-Lee|Tim]] first, were very much opposed. It had to remain completely declarative. Maybe, but the net result is that the programming-vacuum filled itself with the most horrible kluge in the history of computing: Javascript.|[[Robert Cailliau]]<ref>[[wikinews:Wikinews:Story preparation/Interview with Robert Cailliau]]</ref>}}
JavaScript was originally developed by [[Brendan Eich]] of Netscape under the name ''Mocha'', which was later renamed to ''LiveScript'', and finally to JavaScript.<ref>{{cite web|last=Krill |first=Paul |url=http://www.infoworld.com/article/08/06/23/eich-javascript-interview_1.html |title=JavaScript creator ponders past, future |publisher=InfoWorld |date=2008-06-23 |accessdate=2009-05-19}}</ref><ref name="computerworld">{{cite web|last=Hamilton|first=Naomi|url=http://www.computerworld.com.au/article/255293/-z_programming_languages_javascript|title=The A-Z of Programming Languages: JavaScript|publisher=computerworld.com.au|date=2008-06-31}}</ref>
LiveScript was the official name for the language when it first shipped in beta releases of Netscape Navigator 2.0 in September 1995, but it was renamed JavaScript in a joint announcement with Sun Microsystems on December 4, 1995
<ref>[http://web.archive.org/web/20070916144913/http://wp.netscape.com/newsref/pr/newsrelease67.html Press release announcing JavaScript], "Netscape and Sun announce Javascript(TM)", PR Newswire, Dec 4, 1995</ref>
when it was deployed in the Netscape browser version 2.0B3.
<ref name="techvision">{{cite web |archiveurl=http://web.archive.org/web/20080208124612/http://wp.netscape.com/comprod/columns/techvision/innovators_be.html |archivedate=2008-02-08 |title=TechVision: Innovators of the Net: Brendan Eich and JavaScript |publisher=Web.archive.org |date= |accessdate=2010-06-14}}</ref>
 
The change of name from LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its [[Netscape Navigator]] [[web browser]].
The final choice of name caused confusion, giving the impression that the language was a spin-off of the [[Java programming language]], and the choice has been characterized by many as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web-programming language.
<ref>{{cite web|url=http://www.webdevelopersnotes.com/basics/languages_on_the_internet.php3 |title=Programming languages used on the Internet and the World Wide Web (WWW) |publisher=Webdevelopersnotes.com |date= |accessdate=2009-05-19}}</ref>
<ref>{{cite web|url=http://safari.oreilly.com/0596101996/jscript5-CHP-1 |title=O'Reilly - Safari Books Online - 0596101996 - JavaScript: The Definitive Guide, 5th Edition |publisher=Safari.oreilly.com |date= |accessdate=2009-05-19}}</ref>
It has also been claimed that the language's name is the result of a co-marketing deal between [[Netscape]] and [[Sun Microsystems|Sun]], in exchange for Netscape bundling Sun's Java runtime with their then-dominant [[web browser|browser]].{{Citation needed|date=November 2009}}
 
JavaScript very quickly gained widespread success as a client-side scripting language for web pages. As a consequence, [[Microsoft]] developed a compatible dialect of the language, naming it [[JScript]] to avoid trademark issues. JScript added new date methods to fix the [[Year 2000 problem|Y2K]]-problematic methods in JavaScript, which were based on Java's <code>[http://java.sun.com/j2se/1.4.2/docs/api/java/util/Date.html java.util.Date]</code> class.<ref name="popularity">{{cite web|url=http://weblogs.mozillazine.org/roadmap/archives/2008/04/popularity.html |title=Brendan's Roadmap Updates: Popularity |publisher=Weblogs.mozillazine.org |date= |accessdate=2009-05-19}}</ref> JScript was included in [[Internet Explorer]] 3.0, released in August 1996. The dialects are perceived to be so similar that the terms "JavaScript" and "JScript" are often used interchangeably. Microsoft, however, notes dozens of ways in which JScript is not ECMA-compliant.<ref name="JScript_Non-ECMA">[http://msdn2.microsoft.com/en-us/library/4tc5a343.aspx Microsoft JScript Features - Non-ECMA]</ref>
 
In November, 1996 Netscape announced that it had submitted JavaScript to [[Ecma International]] for consideration as an industry standard, and subsequent work resulted in the standardized version named [[ECMAScript]].<ref>[http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf ECMAScript 3rd Edition specification]</ref>
 
JavaScript has become one of the most popular programming languages on the web. Initially, however, many professional programmers denigrated the language because its target audience was web authors and other such "amateurs", among other reasons.<ref>{{cite web|url=http://www.crockford.com/javascript/javascript.html |title=JavaScript: The World's Most Misunderstood Programming Language |publisher=Crockford.com |date= |accessdate=2009-05-19}}</ref> The advent of [[Ajax (programming)|Ajax]] returned JavaScript to the spotlight and brought more professional programming attention. The result was a proliferation of comprehensive [[List of JavaScript libraries|frameworks and libraries]], improved JavaScript programming practices, and increased usage of JavaScript outside of web browsers, as seen by the proliferation of [[server-side JavaScript]] platforms.
 
In January 2009 the [[CommonJS]] project was founded with the goal of specifying a common standard library mainly for JavaScript development outside the browser.<ref>{{cite web |url=http://arstechnica.com/web/news/2009/12/commonjs-effort-sets-javascript-on-path-for-world-domination.ars |title=CommonJS effort sets JavaScript on path for world domination |author=Kris Kowal |date=1 December 2009 |work=[[Ars Technica]] |publisher=[[Condé Nast Publications]] |accessdate=18 April 2010}}</ref>
 
==Trademark==
"JavaScript" is a [[trademark]] of [[Oracle Corporation]]. It is used under license for technology invented and implemented by Netscape Communications and current entities such as the [[Mozilla Foundation]].<ref>{{cite web|title=Sun Trademarks|url=http://www.sun.com/suntrademarks/|publisher=Sun Microsystems|accessdate=2007-11-08}}</ref>
 
==Features==
The following features are common to all conforming ECMAScript implementations, unless explicitly specified otherwise.
 
===Imperative and structured===
JavaScript supports all the [[structured programming]] syntax in [[C (computer language)|C]] (e.g., <code>if</code> statements, <code>while</code> loops, <code>switch</code> statements, etc.). One partial exception is [[scope (computer science)|scoping]]: C-style block-level scoping is not supported (instead, JavaScript has function-level scoping). JavaScript 1.7, however, supports block-level scoping with the <code>let</code> keyword. Like C, JavaScript makes a distinction between [[Expression (programming)|expressions]] and [[Statement (programming)|statements]]. One syntactic difference from C is [[JavaScript syntax#Whitespace and semicolons|automatic semicolon insertion]], in which the semicolons that terminate statements can be omitted.{{Sfn |Flanagan|2006| p=16}}
 
===Dynamic===
; dynamic typing: As in most scripting languages, [[type system|types]] are associated with [[value (computer science)|values]], not with [[Variable (programming)|variables]]. For example, a variable <code>x</code> could be bound to a number, then later rebound to a [[string (computer science)|string]]. JavaScript supports various ways to test the type of an object, including [[duck typing]].{{Sfn |Flanagan|2006| pp=176–178}}
; object based: JavaScript is almost entirely [[object-based]]. JavaScript [[Object (computer science)|objects]] are [[associative array]]s, augmented with prototypes (see below). Object property names are string keys: <code>obj.x&nbsp;=&nbsp;10</code> and <code>obj["x"]&nbsp;=&nbsp;10</code> are equivalent, the dot notation being [[syntactic sugar]]. Properties and their values can be added, changed, or deleted at run-time. Most properties of an object (and those on its prototype inheritance chain) can be enumerated using a <code>for...in</code> loop. JavaScript has a small number of built-in objects such as <code>Function</code> and <code>Date</code>.
; run-time evaluation: JavaScript includes an [[eval]] function that can execute statements provided as strings at run-time.
 
===Functional===
; first-class functions: [[Subroutine|Functions]] are [[first-class function|first-class]]; they are objects themselves. As such, they have properties and methods, such as <code>length</code> and <code>call()</code>;{{Sfn |Flanagan|2006| pp=137&ndash;139}} and they can be assigned to variables, passed as arguments, <code>return</code>ed by other functions, and manipulated like any other object.{{Sfn |Flanagan|2006| p=134}} Any reference to a function allows it to be invoked using the <code>()</code> operator.{{Sfn |Flanagan|2006| p=81}}
; nested functions: 'Inner' or 'nested' functions are functions defined within another function. They are created each time the outer function is invoked. In addition to that, the [[Scope (programming)|scope]] of the outer function, including any constants, local variables and argument values, become part of the internal state of each inner function object, even after execution of the outer function concludes.{{Sfn |Flanagan|2006| p=141}}
; closures: JavaScript allows nested functions to be created, with the [[lexical scope]] in force at their definition, and has a <code>()</code> operator to invoke them now or later. This combination of code that can be executed outside the scope in which it is defined, with its own scope to use during that execution, is called a [[Closure (computer science)|closure]] in computer science.{{Sfn |Flanagan|2006| p=144}}
 
===Prototype-based===
; prototypes: JavaScript uses [[prototype-based programming|prototypes]] instead of [[Class (computer science)|classes]] for [[Inheritance (computer science)|inheritance]]. It is possible to simulate many class-based features with prototypes in JavaScript.
; functions as object constructors: Functions double as object constructors along with their typical role. Prefixing a function call with <code>new</code> creates a new object and calls that function with its local <code>this</code> keyword bound to that object for that invocation. The constructor's <code>prototype</code> property determines the object used for the new object's internal prototype.<!-- this topic is a bit more complex than presented here --> JavaScript's built-in constructors, such as <code>Array</code>, also have prototypes that can be modified.
; functions as methods<!--not sure where to classify this under-->: Unlike many object-oriented languages, there is no distinction between a function definition and a [[method (computer science)|method]] definition. Rather, the distinction occurs during function calling; a function can be called as a method. When a function is called as a method of an object, the function's local <code>this</code> keyword is bound to that object for that invocation.
 
===Miscellaneous===
; run- time environment: JavaScript typically relies on a run-time environment (e.g. in a [[web browser]]) to provide objects and methods by which scripts can interact with "the outside world". In fact, it relies on the environment to provide the ability to include/import scripts (e.g. [[HTML]] <nowiki><script></nowiki> elements). (This is not a language feature per se, but it is common in most JavaScript implementations.)
; variadic functions<!--note: this is not a functional programming feature-->: An indefinite number of parameters can be passed to a function. The function can access them through [[formal parameter]]s and also through the local <code>arguments</code> object.
; array and object literals: Like many scripting languages, arrays and objects (associative arrays in other languages) can each be created with a succinct shortcut syntax. In fact, these [[Object literal|literals]] form the basis of the [[JSON]] data format.
; regular expressions: JavaScript also supports [[regular expression]]s in a manner similar to [[Perl]], which provide a concise and powerful syntax for text manipulation that is more sophisticated than the built-in string functions.
 
===Vendor-specific extensions===
JavaScript is officially managed by [[Mozilla Foundation]], and new language features are added periodically. However, only some non-Mozilla [[JavaScript engine]]s support these new features:
* property getter and setter functions (also supported by WebKit, Opera,<ref>Robert Nyman, [http://robertnyman.com/2009/05/28/getters-and-setters-with-javascript-code-samples-and-demos/ Getters And Setters With JavaScript – Code Samples And Demos], published 29 May 2009, accessed 2 January 2010.</ref> ActionScript, and Rhino)<ref>John Resig, [http://ejohn.org/blog/javascript-getters-and-setters/ JavaScript Getters and Setters], 18 July 2007, accessed 2 January 2010</ref>
* conditional <code>catch</code> clauses
* iterator protocol adopted from [[Python (programming language)|Python]]
* shallow [[Generator (computer science)|generators]]/[[coroutine]]s also adopted from Python
* [[List comprehension|array comprehensions]] and generator expressions also adopted from Python
* proper block scope via the new <code>let</code> keyword
* array and object destructuring (limited form of [[pattern matching]])
* concise function expressions (<code>function(args) expr</code>)
* [[ECMAScript for XML]] (E4X), an extension that adds native XML support to ECMAScript
 
==Syntax and semantics==
{{Main|JavaScript syntax}}
 
As of 2009, the latest version of the language is JavaScript 1.8.1. It is a superset of [[ECMAScript]] (ECMA-262) Edition 3. Extensions to the language, including partial [[E4X]] (ECMA-357) support and experimental features considered for inclusion into future ECMAScript editions, are documented here.<ref>{{cite web|url=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:About |title=About - MDC |publisher=Developer.mozilla.org |date=2008-08-31 |accessdate=2009-05-19}}</ref>
 
===Simple examples===
A simple [[recursion|recursive]] function:
<source lang="JavaScript">
function factorial (n) {
if (n == 0)
return 1;
else
return n * factorial(n-1);
}
</source>
A simple personalised [[greeting]] script:
<source lang="JavaScript">
var name=prompt ("What is your name?")
alert("Welcome "+name)
</source>
 
[[Anonymous function]] (or lambda) syntax:
<source lang="JavaScript">
function add(i, j) {
var add_pri = function(x, y) {
return x + y
};
 
return add_pri(i, j);
}
</source>
 
[[Closure (Computer Science)|Closure]]s:
<source lang="JavaScript">
function showclosure() {
 
var inc = makeinc(1);
 
inc(); //1
inc(); //2
inc(); //3
}
 
function makeinc(initialValue) {
 
var count = initialValue
return function() {
return count++;
};
}
</source>
 
[[Variadic function]] demonstration. This will alert with 1 then 2 then 3. <tt>arguments</tt> is a special [[variable (programming)|variable]].
<source lang="JavaScript">
function unlimited_args() {
 
for( var i = 0; i < arguments.length; i++ ) {
alert(arguments[i]);
}
}
 
unlimited_args(1,2,3);
 
</source>
 
===Example - syntax and semantics===
 
This sample code showcases various JavaScript features. The example can be executed with the following steps: (1) Copy the code to a file with extension <code>.html</code>. (2) Use [[Mozilla Firefox]] or [[Google Chrome]] to open the file.
 
<source lang="JavaScript">
<html>
<head><title>LCM Calculator</title></head>
<body style="font-family:'Courier New'">
<script type="text/javascript">
/* Finds the lowest common multiple of two numbers */
function LCMCalculator(x, y) { // constructor function
function checkInt(x) { // inner function
if (x % 1 != 0)
throw new TypeError(x + " is not an integer"); // exception throwing
return x;
}
//semicolons are optional (but beware since this may cause consecutive lines to be
//erroneously treated as a single statement)
this.a = checkInt(x)
this.b = checkInt(y)
}
// The prototype of object instances created by a constructor is
// that constructor's "prototype" property.
LCMCalculator.prototype = { // object literal
gcd : function() { // method that calculates the greatest common divisor
// Euclidean algorithm:
var a = Math.abs(this.a), b = Math.abs(this.b), t;
if (a < b) {
t = b; b = a; a = t; // swap variables
}
while (b !== 0) {
t = b;
b = a % b;
a = t;
}
// Only need to calculate gcd once, so "redefine" this method.
// (Actually not redefinition - it's defined on the instance itself,
// so that this.gcd refers to this "redefinition" instead of LCMCalculator.prototype.gcd.)
// Also, 'gcd' == "gcd", this['gcd'] == this.gcd
this['gcd'] = function() { return a; };
return a;
},
"lcm" /* can use strings here */: function() {
// Variable names don't collide with object properties, e.g. |lcm| is not |this.lcm|.
// not using |this.a * this.b| to avoid FP precision issues
var lcm = this.a / this.gcd() * this.b;
// Only need to calculate lcm once, so "redefine" this method.
this.lcm = function() { return lcm; };
return lcm;
},
toString : function() {
return "LCMCalculator: a = " + this.a + ", b = " + this.b;
}
};
 
// Note: Array's map() and forEach() are predefined in JavaScript 1.6.
// They are currently not available in the JScript engine built into
// Microsoft Internet Explorer, but are implemented in Firefox, Chrome, etc.
// They are used here to demonstrate JavaScript's inherent functional nature.
 
[[25,55],[21,56],[22,58],[28,56]].map(function(pair) { // array literal + mapping function
return new LCMCalculator(pair[0], pair[1]);
}).sort(function(a, b) { // sort with this comparative function
return a.lcm() - b.lcm();
}).forEach(function(obj) {
/* Note: print() is a JS builtin function available in Mozilla's js CLI;
* It is functionally equivalent to Java's System.out.println().
* Within a web browser, print() is a very different function
* (opens the "Print Page" dialog),
* so use something like document.write() or alert() instead.
*/
// print (obj + ", gcd = " + obj.gcd() + ", lcm = " + obj.lcm());
// alert (obj + ", gcd = " + obj.gcd() + ", lcm = " + obj.lcm());
document.write(obj + ", gcd = " + obj.gcd() + ", lcm = " + obj.lcm() + "<br>");
});
 
</script>
<noscript>
(Message from JavaScript example) <br>
Your browser either does not support JavaScript, or you have JavaScript turned off.
</noscript>
</body>
</html>
</source>
 
The following output should be displayed in the browser window.
<pre>
LCMCalculator: a = 28, b = 56, gcd = 28, lcm = 56
LCMCalculator: a = 21, b = 56, gcd = 7, lcm = 168
LCMCalculator: a = 25, b = 55, gcd = 5, lcm = 275
LCMCalculator: a = 22, b = 58, gcd = 2, lcm = 638
</pre>
 
If Internet Explorer is used, the example will generate an error. Hence the example illustrates the point that the JScript interpreter in Internet Explorer executes code differently from the JavaScript interpreters in other browsers. (See comments in the source code for details on the relevant differences for this example.)
 
==Use in web pages==
{{Main|Client-side JavaScript}}
{{See also|JavaScript engine|Ajax (programming)}}
 
The primary use of JavaScript is to write functions that are embedded in or included from [[HTML]] pages and that interact with the [[Document Object Model]] (DOM) of the page. Some simple examples of this usage are:
 
* Opening or [[Pop-up ad|popping up]] a new window with programmatic control over the size, position, and attributes of the new window (e.g. whether the menus, toolbars, etc. are visible).
* [[Data validation|Validating]] input values of a [[form (web)|web form]] to make sure that they are acceptable before being submitted to the server.
* Changing images as the mouse cursor [[Rollover (web design)|moves over them]]: This effect is often used to draw the user's attention to important links displayed as graphical elements.
 
Because JavaScript code can run locally in a user's browser (rather than on a remote server), the browser can respond to user actions quickly, making an application more responsive. Furthermore, JavaScript code can detect user actions which HTML alone cannot, such as individual keystrokes. Applications such as [[Gmail]] take advantage of this: much of the user-interface logic is written in JavaScript, and JavaScript dispatches requests for information (such as the content of an e-mail message) to the server. The wider trend of [[AJAX|Ajax programming]] similarly exploits this strength.
 
A [[JavaScript engine]] (also known as ''JavaScript interpreter'' or ''JavaScript implementation'') is an [[interpreter (computing)|interpreter]] that interprets JavaScript [[source code]] and executes the [[computer program|script]] accordingly. The first JavaScript engine was created by [[Brendan Eich]] at [[Netscape Communications Corporation]], for the [[Netscape Navigator]] [[web browser]]. The engine, code-named [[SpiderMonkey (JavaScript engine)|SpiderMonkey]], is implemented in [[C (programming language)|C]]. It has since been updated (in JavaScript 1.5) to conform to ECMA-262 Edition 3. The [[Rhino (JavaScript engine)|Rhino]] engine, created primarily by Norris Boyd (formerly of Netscape; now at Google) is a JavaScript implementation in [[Java (programming language)|Java]]. Rhino, like SpiderMonkey, is ECMA-262 Edition 3 compliant.
 
A web browser is by far the most common host environment for JavaScript. Web browsers typically use the public [[application programming interface|API]] to create "host objects" responsible for reflecting the [[Document Object Model|DOM]] into JavaScript. The [[web server]] is another common application of the engine. A [[Server-side JavaScript|JavaScript webserver]] would expose host objects representing an [[HTTP]] request and response objects, which a JavaScript program could then manipulate to dynamically generate web pages.
 
Because JavaScript is the only language that the most popular browsers share support for, it has become a [[target language]]{{dn}} for many frameworks in other languages, even though JavaScript was never intended to be such a language.<ref name="computerworld" /> Despite the performance limitations inherent to its dynamic nature, the increasing speed of JavaScript engines has made the language a surprisingly feasible compilation target.
 
=== Example - use in web pages===
 
A minimal example of a standards-conforming web page containing JavaScript (using [[HTML|HTML 4.01]] syntax) would be the following:
<source lang="html4strict">
<script type="text/javascript">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
alert('Hello, World!');
"http://www.w3.org/TR/html4/strict.dtd">
<html/script>
<head><title>simple page</title></head>
<body>
<script type="text/javascript">
document.write('Hello World!');
</script>
<noscript>
<p>Your browser either does not support JavaScript, or you have JavaScript turned off.</p>
</noscript>
</body>
</html>
</source>
 
Код JavaScript магчыма зьмясьціць у атрыбут апрацоўшчака падзеі:
===Compatibility considerations===
<source lang="html4strict"><a href="#" onclick="alert('Hello, World!'); return false;">Hello, World!</a></source>
{{Main|Web interoperability}}
У гэтым выпадку мадальнае акенца зьявіцца, калі карыстальнік націсьне на спасылку.
 
Звычайна код JavaScript пішацца ў асобным файле, які потым падключаецца пры дапамозе атрыбута <code><nowiki>src</nowiki></code>:
Since JavaScript runs in widely varying environments, an important part of testing and debugging it is testing across browsers.
<source lang="html4strict"><script type="text/javascript" src="Шлях да файла з скрыптом"></script></source>
 
== Асноўныя рысы JavaScript ==
The [[Document object model|DOM]] interfaces for manipulating web pages are not part of the ECMAScript standard, or of JavaScript itself. Officially, they are defined by a separate standardization effort by the [[World Wide Web Consortium|W3C]]; in practice, browser implementations differ from the standards and from each other, and not all browsers execute JavaScript.
 
=== Сынтаксыс ===
To deal with these differences, JavaScript authors can attempt to write standards-compliant code which will also be executed correctly by most browsers; failing that, they can write code that checks for the presence of certain browser features and behaves differently if they are not available.<ref>Peter-Paul Koch, [http://www.quirksmode.org/js/support.html Object detection]</ref> In some cases, two browsers may both implement a feature but with different behavior, and authors may find it practical to detect what browser is running and change their script's behavior to match.<ref>Peter-Paul Koch, [http://www.evolt.org/node/23335 Mission Impossible - mouse position]</ref><ref>Peter-Paul Koch, [http://www.quirksmode.org/js/detect.html Browser detect]</ref> Programmers may also use libraries or toolkits which take browser differences into account.
Сынтаксыс JavaScript падобны на сынтаксыс мовы [[C (мова праграмаваньня)|C]]. Праграма на JavaScript гэта набор інструкцыяў і камэнтароў. У адрозьненьне ад C на JavaScript канец інструкцыі не абавязкова павінны пазначацца сымбалем <code>;</code> (кропка з запятой), правільна сфармаваная інструкцыя лічыцца закончанай напрыканцы радка. ''Камэнтары'' ў JavaScript як і ў C могуць быць блёкавыя (адзін ці некалькі радкоў, абмежаваныя <code>/* ... */</code>) і аднарадковыя (ад камбінацыі <code>//</code> да канца радка).
''Інструкцыі'' складаюцца з зарэзэрваваных слоў, зьменных і канстант (літаралаў).
 
=== Зьменныя ===
Furthermore, scripts may not work for some users. For example, a user may:
 
=== Канстанты ===
* use an old or rare browser with incomplete or unusual DOM support,
* use a [[Personal digital assistant|PDA]] or [[mobile phone]] browser which cannot execute JavaScript,
* have JavaScript execution disabled as a security precaution,
* use a speech browser due to, for example, a visual disability.
 
=== Канструкцыі ===
To support these users, web authors can try to create pages which [[Fault-tolerant system|degrade gracefully]] on user agents (browsers) which do not support the page's JavaScript. In particular, the page should remain usable albeit without the extra features that the JavaScript would have added.
 
===Accessibility Функцыі ===
{{Main|Web accessibility}}
Assuming that the user has not disabled its execution, client-side web JavaScript should be written to enhance the experiences of visitors with visual or physical [[Disability|disabilities]], and certainly should avoid denying information to these visitors.{{Sfn |Flanagan|2006| pp=262&ndash;263}}
 
=== Аб'екты ===
[[Screen reader]]s, used by the [[Visual impairment|blind and partially sighted]], can be JavaScript-aware and so may access and read the page DOM after the script has altered it. The HTML should be as concise, navigable and [[Semantic HTML|semantically rich]] as possible whether the scripts have run or not. JavaScript should not be totally reliant on [[Mouse (computing)|mouse]]-specific events so as to deny its benefits to users who either cannot use a mouse or who choose to favor the [[Keyboard (computing)|keyboard]] for whatever reason. Equally, although [[hyperlink]]s and [[Form (web)|webforms]] can be navigated and operated from the keyboard, accessible JavaScript should not require keyboard [[Event (computing)|events]] either. There are device-independent events such as <code>onfocus</code> and <code>onchange</code> that are preferable in most cases.{{Sfn |Flanagan|2006| pp=262&ndash;263}}
 
== Вонкавыя спасылкі ==
JavaScript should not be used in a way that is confusing or disorientating to any web user. For example, using script to alter or disable the normal functionality of the browser, such as by changing the way the back-button or the refresh event work, is usually best avoided. Equally, triggering events that the user may not be aware of reduces the user's sense of control as do unexpected scripted changes to the page content.<ref>{{cite web|title=Creating Accessible JavaScript|url=http://www.webaim.org/techniques/javascript/|publisher=WebAIM|accessdate=8 June 2010}}</ref>
* [http://www.tutorials4javascript.com/ Javascript Tutorials]
* [http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide Дапаможнік па JavaScript 1.5]
 
[[Катэгорыя:Мовы праграмаваньня]]
Often the process of making a complex web page as accessible as possible becomes a [[nontrivial]] problem where issues become matters of debate and opinion, and where compromises are necessary in the end. However, user agents and [[Assistive technology|assistive technologies]] are constantly evolving and new guidelines and relevant information are continually being published on the web.{{Sfn |Flanagan|2006| pp=262&ndash;263}}
 
===Security===
JavaScript and the DOM provide the potential for malicious authors to deliver scripts to run on a client computer via the web. Browser authors contain this risk using two restrictions. First, scripts run in a [[Sandbox (computer security)|sandbox]] in which they can only perform web-related actions, not general-purpose programming tasks like creating files. Second, scripts are constrained by the [[same origin policy]]: scripts from one web site do not have access to information such as usernames, passwords, or cookies sent to another site. Most JavaScript-related security bugs are breaches of either the same origin policy or the sandbox.
 
====Cross-site vulnerabilities====
{{Main|Cross-site scripting|Cross-site request forgery}}
A common JavaScript-related security problem is [[cross-site scripting]], or XSS, a violation of the [[same origin policy|same-origin policy]]. XSS vulnerabilities occur when an attacker is able to cause a target web site, such as an online banking website, to include a malicious script in the webpage presented to a victim. The script in this example can then access the banking application with the privileges of the victim, potentially disclosing secret information or transferring money without the victim's authorization. A solution to XSS vulnerabilities is to use ''HTML escaping'' whenever displaying untrusted data.
 
Some browsers include partial protection against ''reflected'' XSS attacks, in which the attacker provides a URL including malicious script. However, even users of those browsers are vulnerable to other XSS attacks, such as those where the malicious code is stored in a database. Only correct design of Web applications on the server side can fully prevent XSS.
 
XSS vulnerabilities can also occur because of implementation mistakes by browser authors.<ref>MozillaZine, [http://www.mozillazine.org/talkback.html?article=4392 Mozilla Cross-Site Scripting Vulnerability Reported and Fixed]</ref>
 
Another cross-site vulnerability is [[cross-site request forgery]] or CSRF. In CSRF, code on an attacker's site tricks the victim's browser into taking actions the user didn't intend at a target site (like transferring money at a bank). It works because, if the target site relies only on cookies to authenticate requests, then requests initiated by code on the attacker's site will carry the same legitimate login credentials as requests initiated by the user. In general, the solution to CSRF is to require an authentication value in a hidden form field, and not only in the cookies, to authenticate any request that might have lasting effects. Checking the HTTP Referrer header can also help.
 
"JavaScript hijacking" is a type of CSRF attack in which a <script> tag on an attacker's site exploits a page on the victim's site that returns private information such as JSON or JavaScript. Possible solutions include requiring an authentication token in the POST and GET parameters for any response that returns private [[JSON]] (even if it has no side effects); using POST and never GET for requests that return private JSON; and modifying the response so that it can't be used via a <script> tag (by, for example, wrapping the JSON in a JavaScript comment).
 
====Misplaced trust in the client====
Client-server applications, whether they involve JavaScript or not, must recognize that untrusted clients may be under the control of attackers. Thus any secret embedded in JavaScript could be extracted by a determined adversary, and the application author cannot assume that his JavaScript runs as intended, or at all. Some implications:
 
* Web site authors cannot perfectly conceal how their JavaScript operates, because the code is sent to the client, and [[obfuscated code]] can be reverse-engineered.
* JavaScript form validation only provides convenience for users, not security. If a site verifies that the user agreed to its terms of service, or filters invalid characters out of fields that should only contain numbers, it must do so on the server, not only the client.
* Scripts can be selectively disabled, so JavaScript can't be relied on to prevent operations such as "save image".<ref>
{{cite journal
| title = Right-click “protection”? Forget about it
 
| date = 2008-06-17
| url = http://blog.anta.net/2008/06/17/right-click-%e2%80%9cprotection%e2%80%9d-forget-about-it/
| issn = 1797-1993
| accessdate = 2008-06-17 }}
</ref>
* It would be extremely bad practice to embed a password in JavaScript (where it can be extracted by an attacker), then have JavaScript verify a user's password and pass "password_ok=1" back to the server (since the "password_ok=1" response is easy to forge).<ref>For an example of this bad practice, see [http://javascript.internet.com/passwords/ Javascript.internet.com]</ref>
 
====Browser and plugin coding errors====
JavaScript provides an interface to a wide range of browser capabilities, some of which may have flaws such as [[buffer overflow]]s. These flaws can allow attackers to write scripts which would run any code they wish on the user's system.
 
These flaws have affected major browsers including Firefox,<ref>Mozilla Corporation, [http://www.mozilla.org/security/announce/2006/mfsa2006-38.html Buffer overflow in crypto.signText()]</ref> Internet Explorer,<ref>Paul Festa, CNet, [http://news.com.com/2100-1001-214620.html Buffer-overflow bug in IE]</ref> and Safari.<ref>SecurityTracker.com, [http://securitytracker.com/alerts/2006/Mar/1015713.html Apple Safari JavaScript Buffer Overflow Lets Remote Users Execute Arbitrary Code and HTTP Redirect Bug Lets Remote Users Access Files]</ref>
 
Plugins, such as video players, [[Adobe Flash]], and the wide range of [[ActiveX]] controls enabled by default in Microsoft Internet Explorer, may also have flaws exploitable via JavaScript,
and such flaws have been exploited in the past.<ref>SecurityFocus, [http://www.securityfocus.com/bid/19030/info Microsoft WebViewFolderIcon ActiveX Control Buffer Overflow Vulnerability]</ref><ref>Fusion Authority, [http://www.fusionauthority.com/security/3234-macromedia-flash-activex-buffer-overflow.htm Macromedia Flash ActiveX Buffer Overflow]</ref>
 
In Windows Vista, Microsoft has attempted to contain the risks of bugs such as buffer overflows by running the Internet Explorer process with limited privileges.<ref>Mike Friedman, [http://blogs.msdn.com/ie/archive/2006/02/09/528963.aspx Protected Mode in Vista IE7]</ref> [[Google Chrome]] similarly limits page renderers in its own "sandbox."
 
====Sandbox implementation errors====
Web browsers are capable of running JavaScript outside of the sandbox, with the privileges necessary to, for example, create or delete files. Of course, such privileges aren't meant to be granted to code from the web.
 
Incorrectly granting privileges to JavaScript from the web has played a role in vulnerabilities in both Internet Explorer<ref>US CERT, [https://www.kb.cert.org/vuls/id/713878 Vulnerability Note VU#713878: Microsoft Internet Explorer does not properly validate source of redirected frame]</ref> and Firefox.<ref>Mozilla Foundation, [http://www.mozilla.org/security/announce/2005/mfsa2005-41.html Mozilla Foundation Security Advisory 2005-41: Privilege escalation via DOM property overrides]</ref> In Windows XP Service Pack 2, Microsoft demoted JScript's privileges in Internet Explorer.<ref>Microsoft Corporation, [http://technet.microsoft.com/en-us/library/bb457150.aspx#EHAA Changes to Functionality in Microsoft Windows XP Service Pack 2: Part 5: Enhanced Browsing Security]</ref>
 
[[Microsoft Windows]] allows JavaScript source files on a computer's hard drive to be launched as general-purpose, non-sandboxed programs. This makes JavaScript (like [[VBScript]]) a theoretically viable vector for a [[Trojan horse (computing)|Trojan horse]], although JavaScript Trojan horses are uncommon in practice.<ref>For one example of a rare JavaScript Trojan Horse, see Symantec Corporation, [http://www.symantec.com/security_response/writeup.jsp?docid=2003-100111-0931-99 JS.Seeker.K]</ref> (See [[Windows Script Host]].)
 
==Uses outside web pages==
In addition to web browsers and servers, JavaScript interpreters are embedded in a number of tools. 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.
 
=== Embedded scripting language ===
* Apple's [[Dashboard (software)|Dashboard Widgets]], Apple's [[Safari (web browser)|Safari 5]] extensions, Microsoft's [[Microsoft Gadgets|Gadgets]], [[Yahoo! Widgets]], [[Google Desktop#Gadgets .26 plug-ins|Google Desktop Gadgets]], and [[Serence]] [[Klipfolio]] are implemented using JavaScript.
* Adobe's [[Adobe Acrobat|Acrobat]] and Adobe Reader (formerly Acrobat Reader) support JavaScript in [[Portable Document Format|PDF]] files.<ref>{{cite web|url=http://www.adobe.com/devnet/acrobat/javascript.html | accessdate=2009-08-18 | title= JavaScript for Acrobat}}</ref>
* Tools in the [[Adobe Creative Suite]], including [[Adobe Photoshop|Photoshop]], [[Adobe Illustrator|Illustrator]], [[Dreamweaver]] and [[InDesign]], allow scripting through JavaScript.
* [[OpenOffice.org]] office application suite allows for JavaScript as one of its scripting languages.
* The interactive music signal processing software [[Max/MSP]] released by Cycling '74, offers a JavaScript model of its environment for use by developers. It allows much more precise control than the default GUI-centric programming model.
* ECMAScript was included in the [[VRML|VRML97]] standard for scripting nodes of VRML scene description files.
* Some high-end Philips [[universal remote]] panels, including TSU9600 and TSU9400, can be scripted using a JavaScript-based tool called ProntoScript.<ref>[http://www.pronto.philips.com/prontoscript/index.cfm?id=1422 Koninklijke Philips Electronics NV]</ref>
* [[Sphere (program)|Sphere]] is an open source and cross platform computer program designed primarily to make role-playing games that use JavaScript as a scripting language.
* The open-source [http://www.green-eyed-monster.com/reanimator/ Re-Animator] framework allows developing 2D sprite-based games using JavaScript and XML.
* [[Methabot]] is a web crawler that uses JavaScript as scripting language for custom filetype parsers and data extraction using [[E4X]].
* The [[Unity (game engine)|Unity]] game engine supports JavaScript for scripting (in addition to C# and [[Boo (programming language)|Boo]]) via Mono.<ref>{{cite web
|url=http://unity3d.com/unity/features/scripting
|title=Best Of All Worlds
|publisher=unity3d.com
|accessdate=2009-09-12
}}</ref>
* [[DX Studio|DX Studio (3D engine)]] uses the [[SpiderMonkey (JavaScript engine)|SpiderMonkey]] implementation of JavaScript for game and simulation logic.<ref>
{{cite web |url=http://www.dxstudio.com/features_tech.aspx
|title=Technical Specification
|publisher=dxstudio.com
|accessdate=2009-10-20
}}</ref>
* Maxwell Render provides an ECMA standard based scripting engine for tasks automation.<ref>THINK! The Maxwell Render Resourcer Center, [http://think.maxwellrender.com/scripting_references-269.html Scripting References]</ref>
* Google Docs Spreadsheet has a script editor which allows users to create custom formulas, automate repetitive tasks and also interact with other Google products such as Gmail.<ref>Google Apps Script, [http://www.google.com/google-d-s/scripts/scripts.html Welcome to Google Apps Script]</ref>
 
=== Scripting engine ===
* Microsoft's [[Active Scripting]] technology supports [[JScript]] as a scripting language. This is often considered compatible with JavaScript, but Microsoft lists many JScript features that are not compliant with ECMA standards.<ref name="JScript_Non-ECMA"/>
* The [[Java programming language]], in version SE 6 (JDK 1.6), introduced the <code>javax.script</code> package, including a JavaScript implementation based on [[Rhino (JavaScript engine)|Mozilla Rhino]]. Thus, Java applications can host scripts that access the application's variables and objects, much like web browsers host scripts that access the browser's Document Object Model (DOM) for a webpage.<ref>{{cite web|url=http://java.sun.com/javase/6/webnotes/index.html#scripting |title=javax.script release notes |publisher=Java.sun.com |date= |accessdate=2009-05-19}}</ref>{{Sfn |Flanagan|2006| pp=214 et seq}}
* The [[Qt (toolkit)|Qt]] C++ toolkit includes a <code>QtScript</code> module to interpret JavaScript, analogous to Java's <code>javax.script</code> package.<ref>Nokia Corporation, [http://doc.qt.nokia.com/4.6/qtscript.html QtScript Module]</ref>
* Late Night Software's [[JavaScript OSA]] (aka JavaScript for OSA, or JSOSA), is a freeware alternative to [[AppleScript]] for Mac OS X. It is based on the Mozilla 1.5 JavaScript implementation, with the addition of a <code>MacOS</code> object for interaction with the operating system and third-party applications.<ref>[[AppleScript#Open_Scripting_Architecture|Open Scripting Architecture]]</ref>
 
=== Application platform ===
* [[ActionScript]], the programming language used in [[Adobe Flash]], is another implementation of the ECMAScript standard.
* The [[Mozilla]] platform, which underlies [[Mozilla Thunderbird|Thunderbird]], [[Mozilla Firefox|Firefox]] and some other web browsers, uses JavaScript to implement the [[graphical user interface]] (GUI) of its various products.
* [[Adobe Integrated Runtime]] is a JavaScript runtime that allows developers to create desktop applications.
* [[webOS]] uses the [[WebKit]] implementation of JavaScript in its [[SDK]] to allow developers to create stand-alone applications solely in JavaScript.
* [[CA, Inc.]]'s AutoShell cross-application scripting environment is built on JavaScript/[[SpiderMonkey (JavaScript engine)|SpiderMonkey]] with [[preprocessor]] like extensions for command definitions and custom classes for various system related tasks like file i/o, operation system command invocation and redirection and COM scripting.
* [[GNOME Shell]], the shell for the {{nobr|[[GNOME|GNOME 3]]}} desktop environment.<ref>
{{cite web
|url=http://gnomejournal.org/article/74/behind-the-scenes-with-owen-taylor
|title=Behind the Scenes with Owen Taylor
|publisher=The GNOME Journal
|accessdate=2010-01-23
}}</ref> The [[Seed (programming)|Seed]],<ref>[http://devel.akbkhome.com/seed/index.shtml Devel.akbkhome.com]</ref> [http://live.gnome.org/Gjs Gjs] (from [[GNOME|Gnome]]) and [http://xmelegance.org/kjsembed/ Kjsembed]<ref>[http://xmelegance.org/kjsembed/jsref/index.html Xmelegance.org]</ref> (from [[KDE]]) packages are aimed to utilize that{{clarify|date=December 2010}} needs.
 
==Development tools==
Within JavaScript, access to a [[debugger]] becomes invaluable when developing large, non-trivial programs. Because there can be implementation differences between the various browsers (particularly within the [[Document Object Model]]) it is useful to have access to a debugger for each of the browsers that a web application targets.<ref>{{cite web|url=http://www.alistapart.com/articles/advanced-debugging-with-javascript/ |title=Advanced Debugging With JavaScript |publisher=alistapart.com |date=2009-02-03 |accessdate=2010-05-28}}</ref>
 
Script debuggers are available for [[Internet Explorer]], [[Firefox]], [[Safari (web browser)|Safari]], [[Google Chrome]], and [[Opera (web browser)|Opera]].<ref>{{cite web|url=http://javascript.about.com/od/problemsolving/ig/JavaScript-Debugging/ |title=The JavaScript Debugging Console |publisher=javascript.about.com |date=2010-05-28 |accessdate=2010-05-28}}</ref>
 
Three debuggers are available for Internet Explorer: [[Microsoft Visual Studio]] is the richest of the three, closely followed by [[Microsoft Script Editor]] (a component of [[Microsoft Office]]),<ref>[http://msdn2.microsoft.com/en-us/library/aa202668(office.11).aspx JScript development in Microsoft Office 11] (MS InfoPath 2003)</ref> and finally the free [[Microsoft Script Debugger]] which is far more basic than the other two. The free [http://www.microsoft.com/express/vwd/ Microsoft Visual Web Developer Express] provides a limited version of the JavaScript debugging functionality in Microsoft Visual Studio. Internet Explorer has included developer tools since version 8 (reached by pressing the F12 key).
 
Web applications within Firefox can be debugged using the [[Firebug (Firefox extension)|Firebug]] add-on, or the older [[Venkman]] debugger. Firefox also has a simpler built-in Error Console, which logs and evaluates JavaScript. It also logs [[CSS]] errors and warnings.
 
Opera includes a set of tools called DragonFly.<ref>{{cite web|url=http://www.opera.com/dragonfly/|title=Opera DragonFly|publisher=Opera Software}}</ref>
 
[[WebKit]]'s Web Inspector includes a JavaScript debugger<ref>{{cite web|url=http://webkit.org/blog/61/introducing-drosera/ |title=Introducing Drosera - Surfin' Safari |publisher=Webkit.org |date=2006-06-28 |accessdate=2009-05-19}}</ref> in Apple's [[Safari (web browser)|Safari]] and [[Google Chrome]].
 
Some debugging aids are themselves written in JavaScript and built to run on the Web. An example is the program [[JSLint]], developed by [[Douglas Crockford]], currently senior JavaScript architect at Yahoo! who has written extensively on the language. JSLint scans JavaScript code for conformance to a set of standards and guidelines. [https://www.squarefree.com/bookmarklets/webdevel.html Web development bookmarklets] and [http://getfirebug.com/lite.html Firebug Lite] provide variations on the idea of the cross-browser JavaScript console.
 
[http://www.toptensoftware.com/minime MiniME] is an open source JavaScript minifier, obfuscator and code checking tool for the .NET platform.
 
==Versions==
{{See also|ECMAScript#Dialects|ECMAScript#Version correspondence}}
 
{| class="wikitable" border="1" style="font-size: smaller; text-align: center;"
|-
! Version !! Release date !! Equivalent to !! Netscape<br />Navigator !! Mozilla<br />Firefox !! Internet<br />Explorer !! Opera !! Safari !! Google<br />Chrome
|-
| 1.0 || March 1996 || || 2.0 || || 3.0 || || ||
|-
| 1.1 || August 1996 || || 3.0 || || || || ||
|-
| 1.2 || June 1997 || || 4.0-4.05 || || || || ||
|-
| 1.3 || October 1998 || ECMA-262 1<sup>st</sup> edition / ECMA-262 2<sup>nd</sup> edition || 4.06-4.7x || || 4.0 || || ||
|-
| 1.4 || || || Netscape<br />Server || || || || ||
|-
| 1.5 || November 2000 || ECMA-262 3<sup>rd</sup> edition || 6.0 || 1.0 || 5.5 (JScript 5.5),<br />6 (JScript 5.6),<br />7 (JScript 5.7),<br />8 (JScript 5.8) || 6.0-11.0 || 3.0-5 || 1.0-10.0.666
|-
| 1.6 || November 2005 || 1.5 + Array extras + Array and String generics + [[E4X]] || || 1.5 || || || ||
|-
| 1.7 || October 2006 || 1.6 + Pythonic generators + Iterators + let || || 2.0 || || || ||
|-
| 1.8 || June 2008 || 1.7 + [[Generator (computer science)|Generator expressions]] + [[Closure (computer science)|Expression closures]] || || 3.0 || || || ||
|-
| 1.8.1 || || 1.8 + [[JSON#Native_JSON|Native JSON]] support + Minor Updates || || 3.5 || || || ||
|-
| 1.8.2 || June 22, 2009 || 1.8.1 + Minor updates || || 3.6 || || || ||
|-
| 1.8.5 || July 27, 2010 || 1.8.1 + [[ECMAScript]] 5 Compliance || || 4 || 9 || || ||
|}
 
<ref>{{cite web|author=John Resig |url=http://ejohn.org/blog/versions-of-javascript |title=Versions of JavaScript |publisher=Ejohn.org |date= |accessdate=2009-05-19}}</ref>
 
== Related languages and features ==
Since the acceptance of JavaScript as a popular language, several languages and features have developed from it.
 
[[Objective-J]] is a superset of JavaScript that compiles to standard JavaScript. It adds traditional inheritance and [[Smalltalk]]/[[Objective-C]] style dynamic dispatch and optional pseudo-static typing to JavaScript.
 
[[CoffeeScript]] is an alternate syntax for JavaScript intended to be more concise and readable and adding features like array comprehensions and pattern matching. Like Objective-J, it compiles to JavaScript.
 
[[TIScript]] is a superset of JavaScript that adds classes, namespaces and lambda expressions.
 
[[JSON]], or JavaScript Object Notation, is a general-purpose data interchange format that is defined as a subset of JavaScript.
 
Mozilla browsers currently support [[LiveConnect]], a feature that allows JavaScript and Java to intercommunicate on the web. However, Mozilla-specific support for LiveConnect is scheduled to be phased out in the future in favor of passing on the LiveConnect handling via [[NPAPI]] to the Java 1.6+ plug-in (not yet supported on the Mac {{as of|March 2010|lc=on}}).<ref>[http://java.sun.com/javase/6/webnotes/6u10/plugin2/liveconnect/ Java.sun.com]</ref>
 
=== JavaScript and Java ===
A common misconception is that JavaScript is similar or closely related to [[Java (programming language)|Java]]. It is true that both have a C-like syntax, the C language being their most immediate common ancestor language. They are both object-oriented, typically sandboxed (when used inside a browser), and are widely used in client-side Web applications. In addition, JavaScript was designed with Java's syntax and standard library in mind. In particular, all Java keywords were reserved in original JavaScript, JavaScript's standard library follows Java's naming conventions, and JavaScript's Math and Date objects are based on classes from Java 1.0.<ref name="popularity" />
 
However, the similarities end there. Java has static typing; JavaScript's typing is dynamic (meaning a variable can hold an object of any type and cannot be restricted). Java is loaded from compiled bytecode; JavaScript is loaded as human-readable source code. Java's objects are [[Class (computer science)|class]]-based; JavaScript's are prototype-based. JavaScript also has many functional features based on the Scheme language.
 
==See also==
<div style="-moz-column-count:2; column-count:2;">
* [[VBScript]]
* [[Client-side JavaScript]]
** [[Ajax (programming)|Ajax]]
** [[Comparison of JavaScript frameworks]]
** [[Dynamic HTML]]
* [[Comparison of layout engines (ECMAScript)]]
* [[Comparison of JavaScript-based source code editors]]
* [[ECMAScript]]
* [[JavaScript engine]] (Discussion of JavaScript engines (interpreters) with list of engines)
* [[JavaScript OSA]] - A system-level scripting language for the [[Apple Macintosh]]
* [[JavaScript syntax]]
* [[JSAN]]
* [[JScript]]
* [[JSDoc]]
* [[JSLint]]
* [[JSON]]
* [[List of ECMAScript engines]]
* [[Server-side JavaScript]]
* [[Unobtrusive JavaScript]]
</div>
 
==References==
{{Reflist|colwidth=30em}}
 
==Further reading==
{{Refbegin|colwidth=60em}}
*{{cite book |last=Bhangal |first=Sham |coauthors=Jankowski, Tomasz |title=Foundation Web Design: Essential HTML, JavaScript, CSS, PhotoShop, Fireworks, and Flash |year=2003 |publisher=APress L. P. |isbn=1-59059-152-6}}
*{{cite book |last=Burns |first=Joe |coauthors=Growney, Andree S. |title=JavaScript Goodies |year=2001 |publisher=Pearson Education |isbn=0-7897-2612-2}}
*{{cite book |last=Duffy |first=Scott |title=How to do Everything with JavaScript |year=2003 |publisher=Osborne |isbn=0-07-222887-3 }}
*{{cite book |last=Flanagan |first=David |coauthors=Ferguson, Paula |title=JavaScript: The Definitive Guide |edition=4th |year=2002 |publisher=O'Reilly & Associates |location= |isbn=0-596-00048-0 }}
*{{cite book |last=Flanagan |first=David |title=JavaScript: The Definitive Guide |edition=5th |year=2006 |publisher=O'Reilly & Associates |isbn=0-596-10199-6 |ref = harv}}
*{{cite book |last=Goodman |first=Danny |coauthors=Markel, Scott |title=JavaScript and DHTML Cookbook |year=2003 |publisher=O'Reilly & Associates |isbn=0-596-00467-2}}
*{{cite book |last=Goodman |first=Danny |coauthors=Eich, Brendan |title=JavaScript Bible |year=2001 |publisher=John Wiley & Sons |isbn=0-7645-3342-8}}
*{{cite book |last=Harris |first=Andy |title=JavaScript Programming for the Absolute Beginner |year=2001 |publisher=Premier Press |isbn=0-7615-3410-5}}
*{{cite book |last=Heinle |first=Nick |coauthors=Koman, Richard |title=Designing with JavaScript |year=1997 |publisher=O'Reilly & Associates |isbn=1-56592-300-6}}
*{{cite book |last=McDuffie |first=Tina Spain |title=JavaScript Concepts & Techniques: Programming Interactive Web Sites |year=2003 |publisher=Franklin, Beedle & Associates |isbn=1-887-90269-4}}
*{{cite book |last=McFarlane |first=Nigel |title=Rapid Application Development with Mozilla |year=2003 |publisher=Prentice Hall Professional Technical References |isbn=0-13-142343-6}}
*{{cite book |last=Powell |first=Thomas A. |coauthors=Schneider, Fritz |title=JavaScript: The Complete Reference |year=2001 |publisher=McGraw-Hill Companies |isbn=0-07-219127-9}}
*{{cite book |last=Shelly |first=Gary B. |coauthors=Cashman, Thomas J.; Dorin, William J.; Quasney, Jeffrey J. |title=JavaScript: Complete Concepts and Techniques |year=2000 |publisher=Course Technology |location=Cambridge |isbn=0-7895-6233-2}}
*{{cite book |last=Watt |first=Andrew H. |coauthors=Watt, Jonathan A.; Simon, Jinjer L. |title=Teach Yourself JavaScript in 21 Days |year=2002 |publisher=Pearson Education |isbn=0-672-32297-8}}
*{{cite book |last=Vander Veer |first=Emily A. |title=JavaScript For Dummies |edition=4th |year=2004 |publisher=Wiley Pub. |isbn=0-7645-7659-3}}
{{Refend}}
 
==External links==
{{Spoken Wikipedia|En-JavaScript.ogg|2010-12-13}}
{{Wikibooks|JavaScript}}
* [http://yuiblog.com/crockford/ Douglas Crockford's video lectures on JavaScript]
* [http://jibbering.com/faq/ FAQ for Usenet's comp.lang.javascript]
* Mozilla Developer Center
** [https://developer.mozilla.org/en/JavaScript Mozilla's Official Documentation on JavaScript]
** References for Core JavaScript versions: [https://developer.mozilla.org/en/JavaScript/Reference 1.5+]
** [https://developer.mozilla.org/en/JavaScript/New_in_JavaScript overview over new features in JavaScript]
** List of JavaScript releases: versions [https://developer.mozilla.org/en/JavaScript/Reference/About 1.5+]
** [https://developer.mozilla.org/en/A_re-introduction_to_JavaScript Re-Introduction to JavaScript]
* [http://dev.opera.com/articles/javascript/ JavaScript - Opera Developer Community]
{{ECMAScript}}
 
{{DEFAULTSORT:Javascript}}
[[Category:Cross-platform software]]
[[Category:JavaScript]]
[[Category:Prototype-based programming languages]]
[[Category:Object-based programming languages]]
[[Category:Scripting languages]]
[[Category:1995 introductions]]
 
[[af:JavaScript]]
[[ar:جافا سكريبت]]
[[be:JavaScript]]
[[en:JavaScript]]
[[bg:JavaScript]]
[[ca:JavaScript]]
Радок 594 ⟶ 56:
[[et:JavaScript]]
[[el:JavaScript]]
[[en:JavaScript]]
[[es:JavaScript]]
[[eo:Ĝavaskripto]]