JavaScript

from Wikipedia, the free encyclopedia
JavaScript
//Beispiel JavaScript
function halloWelt() {
	alert('Hello World');
}
window.onload = halloWelt;
Basic data
Paradigms : multi-paradigmatic
Publishing year: May 1995
Designer: Brendan Eich
Developer: Brendan Eich
Current  version : ECMAScript 2020   (June 2020)
Typing : weak , dynamic , duck
Important implementations : SpiderMonkey , Rhino , JavaScriptCore , V8
Influenced by: Self , C , Scheme , Perl , Python , Java , Lua
Affected: ActionScript , Haxe , CoffeeScript , Dart , TypeScript
License : BSD

JavaScript ( JS for short ) is a scripting language that was originally developed by Netscape in 1995 for dynamic HTML in web browsers in order to evaluate user interactions, change, reload or generate content and thus expand the possibilities of HTML and CSS . Today JavaScript is also used outside of browsers, for example on servers and in microcontrollers.

The current name of the language originally called LiveScript was created in 1996 from a cooperation between Netscape and Sun Microsystems . Their Java applets , created with the programming language Java , which was also published in 1995 , were integrated into Netscape Navigator using LiveScript . To capitalize on the popularity of Java, LiveScript was renamed JavaScript, although the two languages ​​are very different from each other.

The language core of JavaScript, standardized as ECMAScript ( ECMA 262), describes a dynamically typed , object-oriented , but classless script language. It does justice to all object-oriented programming paradigms, among other things on the basis of prototypes , the declaration of which is made possible from ECMAScript 6 with a syntax similar to that used in class-based programming languages. In JavaScript, object-oriented , procedural or functional programming can be carried out as required .

development

The syntax of JavaScript is similar to C descendants. Despite the name and syntactic similarity, JavaScript has little in common with Java . In JavaScript, for example, inheritance is not supported by classes but by prototypes .

In the past, JavaScript was mainly used on the client side . JavaScript or the ECMAScript implementations, for example, with the Node.js framework and as JScript or JScript .NET in an ASP or ASP.NET environment on Microsoft Internet Information Services also enable server-side applications. Further examples of server-side JavaScript programming are POW and Jaxer, which are based on the Mozilla JavaScript engine SpiderMonkey , V8CGI, which is based on the JavaScript implementation V8 and integrated into the Apache HTTP server , and QML , an extended form of JavaScript for drawing surfaces and animations.

The language is also used as a scripting language for games and application programs, since the language core contains only a few objects and the interpreter required to execute scripts formulated in JavaScript can therefore be kept relatively small.

In addition, JavaScript is used as the lingua franca in the MongoDB database and in microcontrollers.

use

Typical areas of application

Typical areas of application of JavaScript in the web browser are:

  • dynamic manipulation of websites using the Document Object Model
  • Plausibility check ( data validation ) of form entries before transmission to the server
  • Display of dialog windows
  • Sending and receiving data without the browser having to reload the page ( Ajax )
  • Suggest search terms as you type
  • Advertising banners or ticker
  • E-mail address obfuscation to combat spam
  • Change multiple frames at once or remove the page from the frameset
  • Read and write access to cookies and the web storage within the browser

abuse

Some applications that are possible with JavaScript act partly against the wishes of the user or contradict the principle of the slightest surprise . Some browsers therefore offer functions that suppress such JavaScript functions.

Examples:

Notice in the Firefox browser for many dialog windows
  • Concealment of Internet addresses to which a link refers
  • Deactivate the context menu to make it more difficult to save images or the entire page
  • Deactivating the copy function to make it difficult to copy text or pictures
  • Unsolicited (advertising) pop-ups or pop-unders or successive dialog windows that hinder the user
  • Unintentional closing of the browser window
  • Unintentional resizing of the browser window
  • Barrier-free websites are characterized by the fact that they can be used without restrictions as far as possible even when JavaScript is deactivated. The deactivated JavaScript partially limits the usability of a website.
  • Measures that allow a user to be recognized when they visit a website at a later date, bypassing the browser's security settings (see anonymity on the Internet )
  • In the case of vulnerable web applications, JavaScript can also be misused by third parties, for example via XSS (code injection).

history

On September 18, 1995, Netscape released the previous version of Navigator 2.0, a browser with an embedded scripting language, which at that time was called LiveScript and had been developed by Brendan Eich . The language could u. a. Check user form entries before submitting. On December 4, 1995, Netscape and Sun Microsystems announced a cooperation aimed at the interaction of LiveScript directly with Java applets. Sun developed the necessary Java classes, Netscape the LiveConnect interface and renamed the language to JavaScript (JavaScript 1.0). JavaScript has been a trademark of Oracle since it acquired Sun Microsystems .

With the first beta version of Navigator 3.0, Netscape introduced JavaScript 1.1 on April 29, 1996. In the same version there were the innovations to be able to access images and create so-called rollover graphics . LiveConnect was now an integral part of the browser. With the beta version of Internet Explorer  3, Microsoft presented its first JScript-capable browser in May 1996. This was the beginning of the browser war .

With the announcement of the Netscape Communicator , JavaScript 1.2 was published on October 15, 1996, but Netscape Communicator 4.0 with JavaScript 1.2 was not released until June 4, 1997. Also in June 1997, the European Computer Manufacturers Association published its standard ECMA-262 (ECMAScript) which was developed together with Netscape and was supposed to standardize the basic elements of a scripting language. This became the ISO standard ISO / IEC 16262: 1998 Information technology - ECMAScript language specification in April 1998 . On October 1, 1997, Internet Explorer 4 came out, which covered the language scope of JavaScript 1.1. In addition, own extensions were published, which led to differences in compatibility between Navigator and Internet Explorer and provided a DOM-like syntax that made it possible to access all elements of the website and to change them as required.

The JavaScript interpreter Rhino implemented in Java was supplied as part of the Java runtime environment as part of the Java runtime environment as of version 6.0 . In July 1998, with the beta version of Netscape Communicator 4.5, JavaScript 1.3, which was already available in version 4.06 of Netscape Communicator, was released. In October 1998, Netscape introduced JavaScript 1.4. This version was fully compatible with ECMA-262. However, a browser with support for this version did not appear. In April 2000, the Preview Release 1 of Navigator 6 came with JavaScript 1.5 and DOM Level 1. On June 5, 2002, Mozilla 1.0 with JavaScript 1.5 (JavaScript version 1.5 corresponds to ECMA-262 version 3) and on November 29, 2005 Mozilla Firefox 1.5 with JavaScript 1.6, on July 12, 2006 Mozilla Firefox 2.0b1 with JavaScript 1.7 and on December 18, 2007 Mozilla Firefox 3.0b2 with JavaScript 1.8.

Version history of JavaScript

history
version publication Correspondence Netscape Navigator Mozilla Firefox Internet Explorer Opera safari Google Chrome
Older version; no longer supported: 1.0.0 March 1996 2.0 3.0
Older version; no longer supported: 1.1.0 August 1996 3.0
Older version; no longer supported: 1.2.0 June 1997 4.0-4.05
Older version; no longer supported: 1.3.0 October 1998 ECMA-262 1st edition / ECMA-262 2nd edition 4.06-4.7x 4.0
Older version; no longer supported: 1.4.0 Netscape Server
Older version; no longer supported: 1.5.0 November 2000 ECMA-262 3rd edition 6.0 1.0
  • 5.5 (JScript 5.5)
  • 6 (JScript 5.6)
  • 7 (JScript 5.7)
  • 8 (JScript 6)
  • 6.0
  • 7.0
  • 8.0
  • 9.0
Older version; no longer supported: 1.6.0 November 2005 1.5 + Array extras + Array & String generics + E4X 1.5
  • 3.0
  • 3.1
Older version; no longer supported: 1.7.0 October 2006 1.6 + Pythonic generators + Iterators + let + destructuring assignments 2.0
  • 3.2
  • 4.0
1.0
Older version; no longer supported: 1.8.0 June 2008 1.7 + Generator expressions + Expression closures 3.0
Older version; no longer supported: 1.8.1 June 2009 1.8 + minor updates 3.5
Current version: 1.8.2 January 2010 1.8.1 + minor updates 3.6
Current version: 1.8.5 July 2010 1.8.1 + ECMAScript 5 compliance 4th 9.0 (JScript 9.0)

Version history of ECMAScript (ECMA-262)

The current version is version 2020, which was published in June 2020 as "ECMAScript 2020". Annual updates are to follow. The standards are developed on GitHub.

version published on Differences to the previous version editor
Older version; no longer supported: 1 June 1997 first version Guy L. Steele, Jr.
Older version; no longer supported: 2 June 1998 Changes for compatibility with the international standard ISO / IEC 16262 Mike Cowlishaw
Older version; no longer supported: 3 December 1999 Regular expressions , better processing of character strings, control flow, error handling with try / catch, better error handling, better formatting when outputting numbers, etc. are new . Mike Cowlishaw
Older version; no longer supported: 4th canceled Due to disagreement about the future of the language, the further development of the complex draft for ECMAScript 4 was stopped. Some ideas will come back to life in ES6.
Older version; no longer supported: 5 December 2009 In "strict mode" an extended error check is activated. Unclear language constructs of ECMAScript 3 are defused and new features like getter and setter methods, support for JSON etc. are added. Pratap Lakshman , Allen Wirfs-Brock
Older version; still supported: 5.1 June 2011 Complies with the international standard ISO / IEC 16262: 2011, version 3 Pratap Lakshman, Allen Wirfs-Brock
Older version; still supported: 2015 June 2015 New syntax for complex applications such as classes and modules, which can, however, be defined with terminology similar to that in ECMAScript 5 (strict mode). New language components such as for/ ofloops, syntax partly based on Python , etc. The code name is “Harmony” and was called “ECMAscript 6” until shortly before it was passed. Allen Wirfs-Brock
Older version; still supported: 2016 June 2016 **( Power function ) ,,Array.prototype.includes various adaptations to generators, destructive assignments Brian Terlson
Older version; still supported: 2017 June 2017 async/ await, various Objectfunctions Brian Terlson
Older version; still supported: 2018 June 2018 global, import(), Rest / Spread Properties for- await- of(Asynchronous iterator), string padding , ... Brian Terlson
Older version; still supported: 2019 June 2019 Array#{flat,flatMap}, Object.fromEntries, String#{trimStart,trimEnd}, Symbol#description, ... Brian Terlson, Bradley Farias, Jordan Harband
Current version: 2020 June 2020 String.matchAll, BigInt, import(), ... Jordan Harband, Kevin Smith

safety

Sandbox principle

JavaScript is executed in the browser in a so-called sandbox . The effect of this is that in JavaScript you only have access to the objects of the browser and not to the file system. An exception is read access to a file that was <input type="file">selected by the user via the file selection dialog, started with the HTML element .

To prevent security problems such as cross-site scripting , every website or web application is executed in isolation within the browser and data exchange is prevented. Without this protection, it would be possible to execute malicious code on one side that, for example, reads or manipulates bank or login data in other browser windows that are open at the same time.

Certain security-relevant browser functions, such as closing the browser window, hiding and showing toolbars , changing the browser start page , accessing the clipboard or reading out the user's last visited websites, are also protected by mandatory user input.

By default, a script runs as a single thread within a browser . Waiting loops or long calculations should therefore be avoided in JavaScript programs. With Workerobjects it is possible to create additional threads.

Disabling JavaScript

In many JavaScript-enabled browsers, JavaScript can be switched off or individual actions, such as changing the text in the status bar or manipulating browser windows, can be deactivated. With some browsers, this can also be automated by means of extensions that activate and deactivate JavaScript specifically for pages using white and blacklists . As a result, developers cannot rely on JavaScript programs to behave the same way or even function in every environment.

Language elements

Data types

JavaScript is typed dynamically , which means that the assignment of values ​​to variables is not subject to any type-based restrictions. However, there are various extensions to JavaScript that require static typing as an option or mandatory, for example TypeScript from Microsoft .

Due to the dynamic typing, the data type is not a property of a variable, but rather the property of its current value (or the property of a literal ) in relation to the runtime . The data type of a value can be determined with the unary operator typeof.

Primitive data types

The primitive data types include values ​​for numbers, strings, Boolean values, and symbols. Character strings have the type String ( typeofsupplies "string"), numeric values ​​the type Number ( typeofsupplies "number"), Boolean values the type Boolean ( typeofsupplies "boolean"). Another, albeit seldom used, primitive data type is symbol , which functions ( delivers ) as an identifier (see also keyword symbol ). typeof"symbol"

A special case is the type Undefined with undefinedthe only value ( typeofreturns "undefined").

Not primitive data types

Functions are not a primitive type; typeofsupplies "function". For all other values ​​- nullincluding regular expressions, arrays and the value - returns typeofthe string value "object". Unlike other programming languages, there are no real associative arrays in JavaScript .

Objects created with the predefined constructor functions String() , Number()and Boolean()behave like values ​​of the corresponding data types - but the typeofoperator "object"returns. Such objects are known as wrapper objects . There is no constructor function with the same name for the symbol data type . The following is an example of a variable and the corresponding wrapper object:

let variable = "Beispieltext";
// Die Funktion "alert" gibt das Ergebnis "string" in einem Fenster aus.
alert(typeof variable);

variable = new String("Beispieltext");
alert(typeof variable); // ergibt "object"

Conversely, values ​​of the primitive types Number , Boolean and String are automatically converted into objects of the corresponding constructor function if necessary:

let variable = "Beispieltext";
alert(variable.length); // ergibt 12

Control structures

JavaScript knows the usual control structures . If these should contain more than one statement , a block enclosed in curly brackets must be used. Instructions are terminated with a semicolon, but in most cases this is optional; the automatic semicolon insertion usually completes it automatically.

if-else (conditional statement)

if (bedingung) {
    anweisungen;
} else {
    anweisungen;
}

Abbreviation for conditional value assignments:

variable = bedingung ? wertWennWahr : wertWennFalsch;

switch control structure

switch (variable) {
    case wert1:
        anweisungen;
        break;
    case wert2:
        anweisungen;
        break;
    default:
        anweisungen;
}

while loop

while (bedingung) {
    anweisungen;
}

do-while loop

do {
    anweisungen;
} while (bedingung);

for loop

for (startausdruck; bedingung; iterationsausdruck) {
    anweisungen;
}

for ... in loop

With this instruction all own and inherited properties of an object are run through, which have the internal attribute Enumerable. This attribute was introduced in ECMA Script 5 and is not set for certain built-in properties (such as the function toString of the prototype Object), but it can usually be set (and removed) by the user. The property name is assigned to a specified variable with each loop pass.

for (let eigenschaftsname in objekt) {
    anweisungen;
}

for… of loop

This control structure works like a for… in loop, with the difference that the specified variable is not assigned the property name, but the property value.

for (let wert of objekt) {
    anweisungen;
}

variables

Variables should be declared in JavaScript with letor varand are then valid within the scope in which they were declared, whereby letthe scope is further limited than var. If you use variables without explicitly declaring them beforehand, they are implicitly declared as properties of the global object (in the browser window); this behavior can be prevented by the instruction "use strict";. A special feature of JavaScript is the hoisting of variables, which ensures that all variables and functions declared in a code section are automatically brought up to the beginning during processing (only the declaration, but not their value assignment).

Scope of variables

Variables declared within functions or as function parameters have local validity; Variables declared outside of functions are globally valid. Global for JavaScript in browsers means that variables declared in this way are valid for the entire website and for all active JavaScripts. Since this can lead to unwanted side effects with other scripts integrated in the page (such as third-party plugins, web analytics or advertising banners), global variables should be avoided as far as possible.

let a, b;               // explizite Deklaration einer globalen Variable
a = 1;                  // Definition einer Variable
console.log(a);         // ergibt 1

c = 2;                  // implizite Deklaration ohne let - es entsteht keine Variable, sondern ...
console.log(c);         // ergibt 2
console.log(window.c);  // ... dem globalen Objekt (Window) wurde eine Eigenschaft zugewiesen
console.log(window.a);  // Fehler

function foo(e) {       // saubere Deklaration eines Funktionsparameters
    let f, g = 5;       // saubere Deklaration und Definition einer lokalen Variablen
    console.log(a);     // globale Variablen sind überall gültig
    console.log(c);     // Eigenschaften des globalen Objektes auch
    console.log(e);     // Funktionsparameter haben denselben Gültigkeitsbereich wie lokale Variablen
    h = 7;              // das implizit deklarierte h ist eine globale Variable
}

foo(a);

console.log(e);           // Fehler, da der Funktionsparameter e nur innerhalb der Funktion gültig ist
console.log(f);           // Fehler, da die Variable f nur innerhalb der Funktion gültig ist

console.log(h);           // ergibt 7 - (s.o.)
console.log(window.h);    // ergibt 7 - die globale Variable ist eine Eigenschaft von window

Constants

Constants should also be constdeclared, a value must be assigned to them during initialization. The same conditions apply to the area of ​​validity as for variable declarations with let. Constants cannot be changed by reassigning them, but - if the constants are objects - individual properties of the constants can be changed.

Functions

Functions are full-fledged objects in JavaScript. They have methods and properties, can be created and overwritten, passed as arguments to functions, and can be created and returned by them.

In the latter case, a closure is created , also called a function closure , with which, for example, data encapsulation can be implemented:

let nachricht = function() {
    let geheim = 42;

    return function() {
        return geheim;
    };
};

// botschaft ist eine von nachricht zurückgegebene Funktion
let botschaft = nachricht();
alert(typeof geheim); // undefined
alert(botschaft()); // 42

Not every argument of a function has to be specified when calling it. The value undefined is set for missing arguments . argumentsThe arguments can also be accessed within the function via the object.

generation

There are several ways to create functions in JavaScript:

  • Function declarations ("Function Declarations"):
function f(x, y) {
    return x + y;
}
  • Function expressions:
let f = function(x, y) {
    return x + y;
};
  • Function expressions executed immediately ("Immediately-Invoked Function Expressions"):

Anonymous functions can also be executed directly without first assigning them to a variable. This can be used to encapsulate the scope of variables.

(function(x, y) {
    return x + y;
})(2, 3);
  • Named Function Expressions:

fA function with an identifier is gassigned to the variable . Outside of the function she can be faddressed with , inside with fand g.

let f = function g(x, y) {
    return x + y;
};
  • Function Constructors:
let f = new Function('x', 'y', 'return x + y;');
  • Arrow Functions:

The round brackets are optional if the function has exactly one argument. If the curly braces are omitted, you have to specify exactly one expression without return as the return value. Any code can be specified with curly brackets, but must use return for return values.

(x, y) => x + y;
(x, y) => { return x + y; };
x => x + 1;
x => { return x + 1; };

// Eine so erzeugte Funktion kann man natürlich auch einer Variablen zuweisen
let f = (x, y) => x + y;

example

A functional and recursive implementation of the Euclidean algorithm with two arguments looks like this:

function euklid(a, b) {
    if (b === 0)
        return a;

    return euklid(b, a % b);
}

Implementation of the Euclidean algorithm with any number of arguments:

function ggT(...numbers) {
    if (numbers.length === 0) // (1.)
        return 0;

    if (numbers.length === 1) // (2.)
        return numbers[0];

    return numbers.reduce(euklid); // (3.)
}

console.log(ggT());           // 0
console.log(ggT(4));          // 4
console.log(ggT(24, 36, 84)); // 12
  1. If called ggTwithout an argument, then zero is returned.
  2. If the ggTcall is made with exactly one argument, then the argument itself is returned. This is also known as identity .
  3. Reduced numbersto a single value by reducing two elements at a time from left to right with reduceand euklid.

Implementation of the Euclidean algorithm with partial application:

function ggT(first) {
    if (first === undefined)
        return 0;

    return function(second) {
        if (second === undefined)
            return first;

        return ggT(euklid(first, second));
    };
}

console.log(ggT());             // 0
console.log(ggT(4)());          // 4
console.log(ggT(24)(36)(84)()); // 12

Objects

Objects in JavaScript consist of properties that are implemented as name / value pairs. No distinction is made between attributes and methods of the object (a property whose value has the Function type acts as a method). Every object - even objects created by literals - inherits from the prototype of the global object constructor.

Predefined objects

JavaScript knows several built-in objects and object types that are defined in the ECMAScript standard. An object type is represented by a constructor function with the same name , which can be used to create objects of the corresponding type and which also contains a reference to the prototype of the object type.

  • The nameless global object that contains all variables and objects.
  • The object type Objectfrom which all objects are derived.
  • The object type Functionof functions .
  • The object type Arrayof arrays .
  • The object type Stringof strings .
  • The object type Booleanof Boolean variables .
  • The object type Numberof numbers (64-bit floating point numbers according to IEEE 754 ).
  • The object type Datefor date formats ( dates or times).
  • The object type RegExpfor regular expressions .
  • The object type Errorfor characterizing (and possibly subsequent triggering by means of throw) runtime errors .
  • The object Mathprovides constants and methods for mathematical operations.
  • The object JSONprovides two methods for serializing objects into JSON format and vice versa.
  • The object Reflectprovides methods for determining and changing the metadata of an object.

Other objects that are used in client-side JavaScript, emerged historically mainly by Netscape specifications ( window, documentetc.). The windowobject itself is de facto the global object by simply assigning windowthe global object to a variable . Several sub-objects of documenthave now been through DOM standardized HTML ( title, images, links, formsetc.). Current browsers also support DOM Core and other W3C DOM standards as well as extensions to Microsoft JScript .

Access to object properties and methods

Properties of objects (also methods are properties) can be addressed as follows:

Dot notation (with static identifiers )
objekt.eigenschaft;

objekt.methode(parameter1, parameter2);
Bracket notation (with dynamic identifiers )
objekt["eigenschaft"];

objekt["methode"](parameter1, parameter2);

// Eigenschaftsname, der in Punktnotation illegal wäre
objekt["methode 1"]();

// So können auch alle Eigenschaften des Objekts durchlaufen werden
for (let eigenschaftsName in objekt) {
    console.log(eigenschaftsName, " = ", objekt[eigenschaftsName]);
}

New properties can be added to all objects at runtime or deleteexisting ones can be removed with:

// Statisch bzw. dynamisch benannte Eigenschaften hinzufügen:
objekt.eigenschaftA = "ein Wert";
objekt["eigenschaftB"] = "ein anderer Wert";

// Statisch bzw. dynamisch benannte Eigenschaften entfernen:
delete objekt.eigenschaftA;
delete objekt["eigenschaftB"];

Object literals

Objects can be defined in JavaScript directly based on their properties:

let meinObjekt = {
    zahl: 42,
    gibZahl: function() {
        return this.zahl;
    }
};

alert(meinObjekt.gibZahl()); // 42

There is a special notation for regular expressions:

// mit Konstruktorfunktion
(new RegExp("a")).test("ab"); // true

// als Literal
/a/.test("ab"); // true

Constructor functions

A function can be used newto initialize an object created with. In this case one speaks of a constructor or a constructor function. Within this function, the new object can be thisaddressed via the variable .

function MeinObjekt(x) { // Konstruktor
    this.zahl = x;
}

let objekt = new MeinObjekt(3); // Instanz erzeugen
alert(objekt.zahl); // per Meldefenster ausgeben (3)

"Private" properties

Private properties and methods are not explicitly part of the language.

With the help of closures (see functions ) private properties of objects can still be realized:

let erschaffeKatze = function() {
    let lebensZahl = 7;

    let maunz = function() {
        return (lebensZahl > 0) ? "miau" : "örks";
    };

    // gibt neues Objekt zurück
    return {
        toeten: function() {
            lebensZahl -= 1;
            alert(maunz());
        }
    };
};

let otto = erschaffeKatze();
otto.toeten(); // miau

Only the toetenmethod of ottoknows the variable lebensZahl. The effect is similar to that of a private property if all methods of the cat are defined in the generating function erschaffeKatze. lebensZahlis then visible for all methods (privileged methods, in the example toeten) and internal functions of the generating function (private methods, in the example maunz), but not externally or from methods that are subsequently attached to the object.

Inheritance via prototypes

Inheritance can be implemented in JavaScript through prototypes. This requires that the prototype property of a constructor function be assigned a prototype object. If an object is created with the constructor function, the corresponding property of the prototype (if available) is returned when a non-existent property of the new object is accessed. Example:

let fisch = {
    augen: 2
};

let Mutantenfisch = function() {
    this.augen = 3;
};

Mutantenfisch.prototype = fisch;

let blinky = new Mutantenfisch();

// eigene Eigenschaft von blinky
alert(blinky.augen); // 3

// blinkys eigene Eigenschaft wird gelöscht
delete blinky.augen;

// blinky hat die Eigenschaft selbst nicht mehr,
// es schimmert die Eigenschaft des Prototyps durch
alert(blinky.augen); // 2

To determine whether an object has a property itself or has inherited it from the prototype, each object (automatically through inheritance from Object) has the hasOwnProperty method:

blinky.hasOwnProperty('augen'); // false

Fixing of object structure and content

The structure of an object obj, which is usually completely dynamic in JavaScript, can be fixed in various ways: After the method has been called Object.preventExtensions(obj), no further attributes and methods can be added. Object.seal(obj)prevents both the extension and the deletion of attributes and methods. The call Object.freeze(obj)fixes both the object structure and the attribute values ​​including the methods against subsequent changes. The relevant status of an object objcan be determined with Object.isExtensible(obj), Object.isSealed(obj)and Object.isFrozen(obj).

It is also possible objto fix only a single attribute of an object . For example, the call

Object.defineProperty(obj, "vorname", {writable:false});

the attribute obj.vornameread-only.

Principles of delegation

JavaScript is a delegation language with both self-executing and direct delegation mechanisms.

Functional objects as roles (traits and mixins)
JavaScript already supports various implementations of the role model based on function objects, such as B. Traits and Mixins . Additional behavior is provided by binding at least one method using the keyword thisin the body of an functionobject. If an object requires additional behavior that cannot be made available to it via the prototype chain, a role can be delegated directly via callor applyto this object.
Object composition and inheritance through delegation
While composition in JavaScript can be covered by this direct delegation, automatic delegation is always used when the interpreter has to migrate up the prototype chain of an object, e.g. B. to find a method associated with this object that does not belong to it directly. As soon as the method is found, it is called in the context of this object. As a result, inheritance in JavaScript is mapped via a self-executing delegation mechanism that prototypeis tied to the property of constructor functions.

Error handling

From version 3, ECMAScript has error handling adopted from Java . The instruction try … catch … finallybegins exceptions ( exceptions ab), which due to an error or throwoccur statement. The syntax is:

try {
    // Anweisungen, in denen Ausnahmen auftreten oder ausgelöst werden können
} catch (exception) {
    // Anweisungsfolge, die im Ausnahmefall ausgeführt wird.
    // In diesem Teil kann die Fehlerbehandlung erfolgen.
} finally {
    // Anweisungsfolge, die anschließend in jedem Fall ausgeführt wird.
}

throw "sample exception"; // wenn verfügbar, besser: Error-Objekt (siehe unten)

At the beginning the instructions in the tryblock are executed. If an exception occurs, the controlcatch flow is immediately redirected to the block with the exception object as a parameter.

The exception block is normally skipped. After the tryblock has been executed (even partially) and, if applicable, the catchblock, the statements in the block are always finallyexecuted. The finally-part can be omitted, alternatively the catch-part.

Some runtime environments such as V8 (and thus Node.js ) and also many web browsers provide separate error objects which, in addition to the error message, can also transport a stack trace and other additional information. To take advantage of these advantages, in the simplest application, change the throwcommand from to . throw "Meldungstext";throw new Error("Meldungstext");

Parentheses around the parameter of the throwcommand are generally not necessary. If they are required in exceptional cases, for example to summarize a parameter distributed over several lines, the possible confusion with a function call can still be avoided by inserting a space between throwand the opening brackets.

JavaScript libraries

There are various libraries and frameworks to facilitate the creation of web applications with the help of JavaScript . A library is a collection of functions that the programmer can use. In addition, a framework requires a certain structure of the programming due to a special degree of abstraction .

Triggered by new concepts like Ajax , a new interest in JavaScript arose since 2004. JavaScript is increasingly used for rich client applications that transfer the look and feel of conventional desktop programs to web-based applications. JavaScript plays a key role when it comes to transferring status information between the browser and the HTTP server without loading a full page. In the course of these new requirements, various libraries have emerged that want to simplify the development of such applications. In addition to Ajax functionalities, most of these libraries offer their own basis for object-oriented programming, an abstraction layer for comfortable work with the DOM and graphic effects such as animations . But even before Ajax was widely used, collections of functions existed to support cross-browser programming.

Well-known JavaScript libraries and frameworks include AngularJS , Dojo Toolkit , Ext JS , jQuery , MooTools , Prototype , Qooxdoo , React , Vue.js and the Yahoo User Interface Library . Moo.fx and Script.aculo.us deal specifically with graphic effects . Separate libraries and frameworks are available for server-side programming using Node.js.

Some libraries and frameworks in particular add additional functions to the language, which are often incorporated into later versions of the specification or, if necessary, retrofit older implementations via polyfill .

See also

literature

Web links

Commons : JavaScript  - collection of images, videos and audio files
Wikibooks: Website Development: JavaScript  - Learning and Teaching Materials
Wiktionary: JavaScript  - explanations of meanings, word origins, synonyms, translations

Specifications

Documentation

Individual evidence

  1. speakingjs.com .
  2. ECMAScript® 2020 Language Specification . Ecma International. June 16, 2020.
  3. Stefan Koch: JavaScript . Introduction, programming and reference - including Ajax. 5th edition. dpunkt.verlag, Heidelberg 2009, ISBN 978-3-89864-594-2 , overview, p. 5-17 (457 pp.).
  4. a b Olaf Göllner: JavaScript for microcontrollers. In: heise online. Verlag Heinz Heise, August 13, 2013, accessed on July 27, 2016 .
  5. a b Olaf Göllner: Tessel: JavaScript developer board for the "Internet of Things". In: heise online. Verlag Heinz Heise, August 15, 2013, accessed on July 27, 2016 .
  6. Stefan Koch: JavaScript . Introduction, programming and reference - including Ajax. 5th edition. dpunkt.verlag, Heidelberg 2009, ISBN 978-3-89864-594-2 , JavaScript in the browser, p. 137-156 (457 pp.).
  7. ^ Jens Ihlenfeld: Node - strictly event-oriented Javascript server. In: Golem.de. November 24, 2009. Retrieved July 27, 2016 .
  8. Steve Champeon: JavaScript: How Did We Get Here? (No longer available online.) In: Web DevCenter. O'Reilly, April 6, 2001; archived from the original July 19, 2016 ; accessed on July 27, 2016 (English). Info: The archive link was inserted automatically and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice. @1@ 2Template: Webachiv / IABot / archive.oreilly.com
  9. Chris Mills: A Short History of JavaScript. In: Web Education Community Group Wiki. W3C, July 27, 2012, accessed July 27, 2016 .
  10. Trademark entry # 75026640 at the USPTO for JavaScript. In: uspto.gov. United States Patent and Trademark Office , May 6, 1997, accessed October 24, 2012 .
  11. Ingo Pakalski: 15 years of the WWW: The Browser Wars . The first browser war brings Netscape to its knees. In: Golem.de. May 1, 2008, accessed July 27, 2016 .
  12. Klaus-Peter Kerbusk: Abuse of the monopoly . In: Der Spiegel . No. 44 , 1997 ( online ).
  13. ^ Scripting for the Java Platform. In: Java SE Documentation. Oracle , accessed October 24, 2012 .
  14. Florian Scholz, Eric Shepherd: New in JavaScript 1.3. In: Mozilla Developer Network. Mozilla Foundation, January 20, 2016, accessed July 27, 2016 .
  15. Florian Scholz, Eric Shepherd: New in JavaScript 1.4. In: Mozilla Developer Network. Mozilla Foundation, January 20, 2016, accessed July 27, 2016 .
  16. New Features in this Release. In: DevEdge Online Documentation. Netscape Communications Corporation, October 29, 1998, archived from the original on August 2, 2004 ; accessed on July 27, 2016 (English).
  17. Florian Scholz, Eric Shepherd: New in JavaScript 1.5. In: Mozilla Developer Network. Mozilla Foundation, accessed January 20, 2016 .
  18. Wladimir Palant, SylvainPasche, Nickolay Ponomarev, Florian Scholz, Eric Shepherd: New in JavaScript 1.6. In: Mozilla Developer Network. Mozilla Foundation, April 4, 2016, accessed July 27, 2016 .
  19. Florian Scholz, James Herdman, Eric Shepherd, Robert Sedovšek, David Bruant, Leo Balter, Jonathan Watt, Eli Gray, Nickolay Ponomarev, Martin Honnen, Evan Prodromou: New in JavaScript 1.7. In: Mozilla Developer Network. Mozilla Foundation, October 21, 2015, accessed July 27, 2016 .
  20. Florian Scholz, Eli Gray, Leandro Mercês Xavier, Nickolay Ponomarev: New in JavaScript 1.8. In: Mozilla Developer Network. Mozilla Foundation, January 20, 2016, accessed July 27, 2016 .
  21. ^ John Resig: Versions of JavaScript. In: johnresig.com/. April 22, 2008, accessed June 8, 2020 .
  22. ECMAScript 2020 Language Specification. June 2020, accessed on June 19, 2020 (English).
  23. Julia Schmidt: The standard for ECMAScript should receive updates every year. In: heise Developer. January 23, 2015, accessed October 22, 2015 .
  24. tc39 / ecma262. In: GitHub. Retrieved January 2, 2017 .
  25. Changes to JavaScript, Part 1: EcmaScript 5
  26. ECMAScript 2015 Language Specification. Accessed January 2, 2017 .
  27. ECMAScript 2016 Language Specification . 7th edition. Emca International, Geneva (English, 586 pages, ecma-international.org [PDF]). ECMAScript 2016 Language Specification ( Memento of the original from April 12, 2015 in the Internet Archive ) Info: The archive link was inserted automatically and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice.  @1@ 2Template: Webachiv / IABot / www.ecma-international.org
  28. ECMAScript 6 compatibility table. In: kangax.github.io. Accessed January 2, 2017 .
  29. Nicholas C. Zakas: Professional JavaScript for Web Developers . John Wiley & Sons., 2011, ISBN 978-1-118-02669-4 (English, 960 pages).
  30. ECMAScript 2017 Language Specification. June 2017, accessed December 5, 2017 .
  31. JavaScript standard ECMAScript 2016 officially adopted. In: heise online. heise Developer, June 17, 2016, accessed on January 3, 2017 .
  32. a b ECMAScript Next compatibility table. In: kangax.github.io. Retrieved January 2, 2017 .
  33. ECMAScript 2017 Language Specification. Ecma International, June 2017, accessed August 4, 2017 .
  34. Christian Liebel: Evolution on the Web: ECMAScript 2017. heise Developer, August 1, 2017, accessed on August 4, 2017 .
  35. ECMAScript 2017. In: Exploring ES2016 and ES2017. March 22, 2017, accessed August 4, 2017 .
  36. JavaScript standard ECMAScript 2018 officially adopted heise.de on June 28, 2018
  37. Tracking ECMAScript Proposals. In: TC39. Ecma, accessed August 4, 2017 .
  38. ECMAScript 2019: Nine innovations for the JavaScript language standard. In: heise online. heise online, February 4, 2019, accessed on April 17, 2020 .
  39. JavaScript: The features for ECMAScript 2020 are fixed. In: heise online. heise online, April 6, 2020, accessed on June 19, 2020 .
  40. W3C Working Draft September 24, 2015. In: w3.org. Retrieved July 28, 2016 .
  41. Ilja Zaglov: TypeScript: Microsoft's new JavaScript extension. In: t3n magazine . October 10, 2012, accessed October 10, 2012 .
  42. JavaScript / Objects / Array. In: selfhtml. July 15, 2016, accessed July 27, 2016 .
  43. for ... in MDN
  44. Object.defineProperty () MDN
  45. for ... of MDN
  46. JavaScript / Variable / let in the SelfHTML Wiki
  47. JavaScript / Variable / const in the SelfHTML Wiki
  48. Juriy Zaytsev Kangax: Named function expressions demystified. In: kangax.github.io. June 17, 2009, accessed July 28, 2016 .
  49. a b ECMAScript Language Specification - ECMA-262 Edition 5.1. In: ecma-international.org. Retrieved July 28, 2016 . ( ecma-international.org PDF).
  50. English Wikipedia: Role-oriented programming
  51. Traits for Javascript , 2010.
  52. CocktailJS - ANNOTATIONS. TRAITS. TALENTS. , April 2013.
  53. Angus Croll, A fresh look at JavaScript Mixins from May 31, 2011.
  54. Being able to generalize the many talents of JavaScript role-oriented programming approaches such as traits and mixins , June 5, 2014.
  55. JavaScript Stack Trace API in Google V8 Wiki , as of June 28, 2010, accessed on February 23, 2013
  56. JavaScript Core Reference: Error ( Memento of November 4, 2014 in the Internet Archive ) in Aptana HTML Reference , as of July 2, 2012, accessed on February 23, 2013
  57. Tom DuPont: Report Unhandled Errors from JavaScript. April 13, 2013, accessed on April 16, 2013 (English, error logging with stack trace in JavaScript).
  58. ^ Nico Reed: What is the error object? ( Memento of the original from March 31, 2013 in the Internet Archive ) Info: The archive link was inserted automatically and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice. In: Nodejitsu Documentation , as of August 26, 2011, accessed on February 23, 2013. @1@ 2Template: Webachiv / IABot / docs.nodejitsu.com
  59. Stefan Koch: JavaScript. Introduction, programming and reference - including Ajax . 5th edition. dpunkt.verlag, Heidelberg 2009, ISBN 978-3-89864-594-2 , Ajax, p. 333-355 (457 pp.).