JavaScript/JScript
Introduction[edit]
Netscape originally developed a scripting language for use in its browsers, calling it LiveScript. For marketing reasons they renamed the scripting language to JavaScript. Microsoft implemented its own version of JavaScript and called it JScript. Netscape, Microsoft and others started standardizing the scripting language, using the ECMA standardizing organisation (http://www.ecma.ch) for that. Thus the language standard is now called ECMA Script. Note that this standard is only about the core language, with data and objects like numbers, strings, booleans, Object, Array, Function, Date, Math, but NOT about application specific objects like browser specific objects (document, window, links, images etc)
- 1999: ES3
- 2009: ES5
- 2015: ES6 (class, constructor, extends, super, ...)
- 2016: ES7
- 2017: ES8
The core features of Netscape's JavaScript and Microsoft's JScript are pretty much compliant with the ECMA Script standard, but the application specific objects like the browser DOM (Document Object Model) and the server object model differ, slightly less with time. Für die folgende Beschreibung wird JS als Synonym zu JavaScript und JScript verwendet. JS-Programme werden wahlweise direkt in der HTML-Datei oder in separaten Dateien notiert. Sie werden nicht - wie etwa Java-Programme - compiliert, sondern als Quelltext zur Laufzeit interpretiert, also ähnlich wie Batchdateien bzw. Shellscripts. Dazu besitzen moderne WWW-Browser wie Netscape oder Microsoft Internet Explorer entsprechende Interpreter-Software.
- JS is an interpreted, object-based scripting language. JavaScript has a prototype-based, object-oriented programming model. It creates objects using other objects as blueprints and to implement inheritance it manipulates what’s called a prototype chain.Although it has fewer capabilities than full-fledged object-oriented languages like C++ and Java, JS is more than sufficiently powerful for its intended purposes.
- JS is a loosely typed language. That means you do not have to declare the data types of variables explicitly. In fact, you cannot explicitly declare data types in JS. Moreover, in many cases JS performs conversions automatically when they are needed. For instance, if you try to add a number to an item that consists of text (a string), the number is converted to text.
- JS has a very powerful handling of associative arrays which is expanded to object properties, which can also be used in for-loops. Any functions can be assigned to and manipulated as a property. They even can be created by the new-operator.
Windows Scripting Host[edit]
Der WSH führt JS-Dateien aus. Um den Code zu strukturieren kann man wsf-Dateien erstellen, die js-Dateien über das Script-Tag includieren.
Language[edit]
JS is case-sensitive language.
HTML embedding[edit]
<script type="text/javascript"> <javascript code> </script>
Comments[edit]
// einzeilig /* mehrzeilig */
Variables[edit]
Although not required, it is considered good practice to declare variables before using them. You do this using the var statement. The only time you must use the var statement is if you want to declare variables that are local to a function. Local variables are those that are only within the function. Re-declaring a variable will not change the value the variable already had. You can declare a variable implicitly (without using var) by assigning a value to it.
The first character must be a letter or an underscore (_), or a dollar sign ($). Variable names are case sensitive.
In instances in which you want to declare a variable and initialize it, but without giving it any particular value, you may assign it a special value, null. If you declare a variable without assigning any value to it, it exists but is undefined. The types are:
- String (can be treated as object)
- Number (can be treated as object)
- Boolean (can be treated as object)
- Array (internally object)
- Object
- Null
- Undefined.
The type of a variable can be checked by:
typeof();
JS supports both integer and floating-point numbers. Integers can be positive, 0, or negative; a floating-point number can contain either a decimal point, an "e" (uppercase or lowercase), which is used to represent "ten to the power of" in scientific notation, or both. These numbers follow the IEEE 754 standard for numerical representation. Last, there are certain number values that are special:
- NaN
- positiv infinity
- negativ infinity
- positiv 0
- negativ 0
Declaration[edit]
var x; var y = 10; // function scope, redeclaration allowed let a; let b = 10; // block scope, redeclaration not allowed
As JS is a loosely-typed language, variables in JS technically have no fixed type. Instead, they have a type equivalent to the type of the value they contain. It is possible, under some circumstances, to force the automatic conversion (or coercion) of a variable or a piece of data into a different type. Numbers can easily be included in strings, but strings cannot be included directly in numbers, so explicit conversion functions, parseInt() and parseFloat(), are provided.
var theFrom = 1;
var theTo = 10;
var doWhat = "Count from ";
doWhat += theFrom + " to " + theTo + ".";
After this code is executed, the doWhat variable contains "Count from 1 to 10." The number data have been coerced into string form.
var nowWhat = 0;
nowWhat += 1 + "10"; // In this case, because "10" is a string,
// the "+=" operator concatenates.
After this code is executed, the nowWhat variable contains "0110". The following steps are followed to arrive at this result:
- Look at the types of 1 and "10". The "10" is a string, the 1 is a number, so the number is coerced into a string.
- As the values on either side of the + operator are both strings, do a string concatenation. This results in "110"
- Look at the types of the values on either side of the +=. nowWhat contains a number, and "110" is a string, so convert the number to a string.
- As there are now strings on either side of the += operator, do a string concatentation. This results in "0110".
- Store this result in nowWhat.
var nowThen = 0;
nowThen += 1 + parseInt("10"); // In this case, "+=" performs addition.
After this code is executed, the nowThen variable contains the integer 11.
Um zu testen ob eine Variable x den Wert ‘undefined’ besitzt sind mir z.Z. zwei Verfahren bekannt.
if (String(x) == "undefined") ... if (typeof(x) == "undefined") ...
Datatypes[edit]
Conversion[edit]
- + unary operator converts to number
Operatoren[edit]
| == | Value Comparison | |
| === | Value and Type Comparison | |
| && | logical AND | |
| logical OR |
Conditional Statements[edit]
if (<Expression)
{
<statements>
}
[else
{
<statements>
}]
Arrays[edit]
Arrays sind Objekte which can contain different objects. Arrays werden durch
var arr = [[( <Number> | <Element> {,<Element>})]];
var arr = new Array([( <Number> | <Element> {,<Element>})]);
var arr = new Array<<TYPE>>(....)
deklariert. In JavaScript, arrays always use numbered indexes. Die Indizierung ist 0-based. Arrays haben eine member variable length. JavaScript does not support associative arrays. If you use a named index, JavaScript will redefine the array to a standard object. After that, all array methods and properties will produce incorrect results.
To empty an array you can:
x.length = 0; // empties an existing array x = []; // creates a new array
To delete an array element without leaving holes use:
x.splice(<index>, <length of array section to delete>);
Methoden der Array-Klasse[edit]
push()[edit]
adds an element at the end
pop()[edit]
removes the last element
splice()[edit]
splice(i,n)
removes n elements starting at i
shift()[edit]
removes the first element
unshift()[edit]
The unshift() method adds new items to the beginning of an array, and returns the new length.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon","Pineapple");
Function Definition[edit]
Internally functions are objects (good explanation). There are multiple ways of defining a function. Die Definition von Funktionen kann überall im Quellcode erfolgen und muss nicht vor der Verwendung erfolgen.
function <FunctionName>(<ParameterList>) // only declaration, no execution
{
<StatementList>;
return <Value|Parameter>;
}
<FunctionName>(); // execution
or
var foo = function() // only declaration, assigning variable to unnamed function object
{
<StatementList>;
return <Value|Parameter>;
}
foo(); // execution
or
var add=new Function("a", "b", "return a+b;"); // very special, not recommended
Functions can be properties of an object.
ASEF/IIFE[edit]
Another way is to create and execute a function created with function expression at once (anonymous self-execting function ASEF) (good explanation), also better named IIFE (Immediately Invoked Function Expression, IIFE)) by adding the parantheses following the function declaration:
(function() { ... })(); // function() { ... })() missing brackets give a syntax error because it is a
// function declaration instead of a function expresssion, only the latter can be executed
(function(aParameter) { alert(aParameter); })("an argument"); // ASEF with parameter, will alert "an argument"
(function($){ alert($(window).jquery); })(jQuery); // avoids conflict with another library defining the $ global variable
All variables and functions defined within the anonymous function aren’t available to the code outside of it, so there is no naming conflict. The parameters are somehow passed by value and are available even if functions within are called later:
// will alert two times with value 2
var f = (function (p)
{
alert(p);
var x = function () { alert(p); };
return { y: x };
})(2);
f.y();
Arrow Function[edit]
Arrow Functions can remove the need of function, return and {} when defining functions. They are one-liners, similar to Lambda Expressions in Java or Python.
Async Funtion[edit]
An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style. Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. E.g.:
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
}
asyncCall();
console.log("asyncCall() called");
prints
> "calling" > "asyncCall() called" > "resolved"
Namespacing[edit]
A good explanations of the patterns can be found here. The standard is to define a new namespace or use the existing one (and not overwrite it) and ASEF style by:
var my_namespace = my_namespace || { };
my_namespace.sub_namespace = (function ()
{
var func1 = function () { ... };
var public = { func1 : func1, ... };
return public;
} ();
Classes[edit]
Classes are just special functions added to ES6 that are meant to mimic the class keyword from these other languages. We can have class declarations and class expressions. Classes are just normal JavaScript functions and could be completely replicated without using the class syntax. It is special syntactic sugar added in ES6 to make it easier to declare and inherit complex objects. Each class can only have one constructor method in it.
class Person { // class declaration
constructor(firstName, lastName) {
this.firstName= firstName;
this.lastName = lastName;
}
}
let Person = class [<Classname>] { // class expression
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
- Getter, Setter and Static Methods
- inheritance and super()
Class Object Creation[edit]
var x = new <ClassName>(<Ctor Parameter>);
Object Declaration[edit]
In JavaScript nearly everything is an object. Objects are complex variables with properties and methods. Each property has a name and a value. In JavaScript, all values except primitive values are objects. Primitive values are:
- strings ("John Doe"),
- numbers (3.14),
- true,
- false,
- null, and
- undefined.
There multiple ways to declare and to instantiate objects
// by ctor function, which is a normal function but used with the new operator
function <ClassName>(<ParameterList>)
{
// declaration of a member/property
this.<MemberName> = <ParameterListElement>;
// declaration of a method
this.<MethodName> = function() { ...};
...
}
// object instantiation
var <NewVar> = new <ClassName>(<ActualParamterList>);
or
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; // creates an object with 4 properties
or
var person = new Object(); person.firstName = "John"; person.lastName = "Doe";
Existing objects can be extended by using the predefined prototype property:
person.prototype.doSomething = function() { ... };
Object Usage[edit]
name = person.lastName; name = person["lastName"];
this[edit]
- In JavaScript, the thing called this, is the object that "owns" the JavaScript code.
- The value of this, when used in a function, is the object that "owns" the function.
- The value of this, when used in an object, is the object itself.
- The this keyword in an object constructor does not have a value. It is only a substitute for the new object.
- The value of this will become the new object when the constructor is used to create an object.
Promises[edit]
The Promise object represents the eventual (irgendwann) completion (or failure) of an asynchronous operation and its resulting value. At their most basic, promises are a bit like event listeners except:
- A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa.
- If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier.
A promise can be:
- fulfilled - The action relating to the promise succeeded
- rejected - The action relating to the promise failed
- pending - Hasn't fulfilled or rejected yet
A promise is said to be settled if it is either fulfilled or rejected, but not pending.
The eventual state of a pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options occur, the associated handlers queued up by a promise's then method are called:
- The .then() method takes up to two arguments; the first argument is a callback function for the fulfilled case of the promise, and the second argument is a callback function for the rejected case. Each .then() returns a newly generated promise object
The Promise.resolve() method "resolves" a given value to a Promise.
Modules[edit]
- some recommend to use *.mjs for modules
- export items by
export ...;
- import items by
import {<ItemList> } from './modules/square.js';
<script type="module" src="main.js"></script>
- can define multiple classes
API[edit]
predefined Objects[edit]
Daß JavaScript eine Erweiterung von HTML darstellt, liegt vor allem an den vordefinierten Objekten, die Ihnen in JavaScript zur Verfügung stehen. Über diese vordefinierten Objekte können Sie beispielsweise einzelne Elemente eines HTML-Formulars abfragen oder ändern. Ein Objekt kann eine Teilmenge eines übergeordneten Objekts sein. Die JavaScript-Objekte sind deshalb in einer Hierarchie geordnet. Das hierarchiehöchste Objekt ist in JavaScript das Fenster-Objekt (window). Fenster haben Eigenschaften wie einen Titel, eine Größe usw. Der Inhalt eines Fensters ist das nächstniedrigere Objekt, nämlich das im Fenster angezeigte Dokument (in JavaScript das Objekt document). In der Regel ist der Fensterinhalt eine HTML-Datei.
HTML DOM objects[edit]
The HTML DOM can be accessed with JavaScript (and with other programming languages). In the DOM, all HTML elements are defined as objects.
document[edit]
The document object is the web page.
getElementByID(IDString)[edit]
The most common way to access an HTML element is to use the id of the element.
// both statements are equivalent
window.document.getElementById("header");
document.getElementById("header");
write(HTMLString)[edit]
The write method can be called only during the loading of the page to insert contents into the parsing of the document.
writeln()[edit]
form[edit]
document.<Formname>.(<Methode>|<Eigenschaft>) document.forms[<Index>].(<Methode>|<Eigenschaft>) document.<Formname>.elements[<Index>].(<Methode>|<Eigenschaft>)
Window Object[edit]
The window object is supported by all browsers. It represent the browser's window. All global JavaScript objects, functions, and variables automatically become members of the window object. Global variables are properties of the window object. Global functions are methods of the window object. Even the document object (of the HTML DOM) is a property of the window object. In coding the window object can be omitted:
Attributes[edit]
- document
openWindow()[edit]
details see here
Strings[edit]
Strings in javascript are represented in Unicode UTF-16 (see here for a detailled discussion). Each character has a code point (char code). Generally each character is represented by 2 bytes (since Unicode 3.0 it can be more bytes). To avoid have files of double size compared to ASCII-coded files the UTF-8 unicode standard was invented which only represents with more than 1 byte if necessary.
var x = new String(""); // new String Object
var y = ""; // new String Literal
var z = ;
Konkatenation[edit]
<String> + <String>;
Methoden[edit]
| String replace(<#Regular_Expressions>,<ReplaceWith>) | returns a new String Object, RegExpression is /.../[<Flags>] |
| Array split(<Seperator>[,MaxSplits]) | |
| String substring(<0-based start index>, [<0-based end index>]) |
Regular Expressions[edit]
Date[edit]
The Date object is used to work with dates and times. Date objects are created with the Date() constructor. There are four ways of initiating a date:
new Date() // current date and time new Date(milliseconds) //milliseconds since 1970/01/01 new Date(dateString) new Date(year, month, day, hours, minutes, seconds, milliseconds)
Methods see here.
RxJs[edit]
- see learn RxJs
- RxJs stands for Reactive Extensions for Javascript
- A stream is a sequence of values in time
- The combination of a stream with a set of functional operators to transform streams leads us to the notion of Observable.
- RxJs is an implementation of Observables for Javascript
- A Pipeable Operator is a function that takes an Observable as its input and returns another Observable. It is a pure operation: the previous Observable stays unmodified.
Observables and Observers[edit]
The observable (e.g. see here type can be used to model push-based data sources such as events, timer intervals and sockets. The Observer pattern is a design pattern in which Subjects maintain a list of Observers (consumers) and notifies them of state changes. It is heavily used in Angular. The biggest difference between observables and promises is that promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from. A handler for receiving observable notifications implements the Observer interface. It is an object that defines callback methods to handle the three types of notifications that an observable can send:
Observer = {
next: ... // required
error: ... // optional
complete: ... // optional
- An observable is said to be cold because it does not generate new values if no subscriptions exist
- $ suffix (popularized by Cycle.js) is used to indicate that the variable is an Observable.
- Creation Operators are the other kind of operator, which can be called as standalone functions to create a new Observable.
// create an observable
timer$ = new Observable<string>( // new observable
observer => { // subscriber function is executed when a consumer calls subscribe() and desribes how to generate values
setInterval(
() => observer.next(new Date().toString()),
10000);
console.log("someone subscribed");
}
);
var subscription: Subscription = timer$.subscribe({ // passing an observer which is an objects that defines the handler for the values it receives
next(datestring) { // implements the Observer interface with callback methods for the 3 types of notifications
console.log(datestring); // next, error and complete
}
});
Subjects[edit]
In addition to Observables you can send to a Subject. A subject you can subscribe to it and you can use it to broadcast to other subscribers any time and anywhere in code. The only place you can broadcast data from observable is inside its constructor.
BehaviorSubject[edit]
Observable is a Generic, and BehaviorSubject is technically a sub-type of Observable because BehaviorSubject is an observable with specific qualities:
- It needs an initial value as it must always return a value on subscription even if it hasn't received a
next() - Upon subscription, it returns the last value of the subject. A regular observable or subject only triggers when it receives an onnext
- at any point, you can retrieve the last value of the subject in a non-observable code using the
getValue()method. - It is an observer in addition to being an observable so you can also send values to a subject in addition to subscribing to it.
pipe()[edit]
The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence e.g.
const source$: Observable<number> = range(0, 10);
source$.pipe(
map(x => x * 2),
filter(x => x % 3 === 0)
).subscribe(x => console.log(x));
prints
0 6 12 18
- pipe needs to return an observable
Tips[edit]
Skript beenden[edit]
WScript.Quit();
Andere Seite laden[edit]
window.location.href = "<URL>";
Seite in anderem Fenster laden[edit]
window.open(<URL>,<TITLE>,width=, height=, resizeable=)
Fokus setzen[edit]
document.<FormName>.<ElementName>.focus();
CheckBox in einer Form prüfen[edit]
document.forms["TestForm"].elements"TestCheckbox".checked
Bei Selektion in Select etwas tun[edit]
<form>
<select onChange="location.href=this.options[this.selectedIndex].value">
<option value="http://www.brauchbar.de/index.html">Bitte wählen
<option value="http://www.brauchbar.de/index.html">Homepage
<option value="http://www.brauchbar.de/wd/index.html">Newsletter
<option value="http://www.brauchbar.de/wd/online/index.html">Archiv
</select>
</form>
Excel steuern[edit]
Das OLE-Automation Objektmodell schaut man sich am besten in der VBA-Entwicklungsumgebung an. s. 1
Access steuern[edit]
Das Access-Objektmodell schaut man sich am besten in einer VBA Entwicklungsumgebung an, nachdem man die Type-Library eingebunden hat (s. 2).
Outlook steuern[edit]
Das Outlook Objektmodell schaut man sich am besten in der VBA-Entwicklungsumgebung an, nachdem man die Type-Library eingebunden hat (s. auch s. 3). Die Hilfe findet sich unter C:\Uwes\OutExch\HelpFiles\Outlook 98\vbaoutl.hlp.
Debugging[edit]
Microsoft Script Debugger[edit]
Der Debugger ist installiert unter C:\Programme\Microsoft Script Debugger\. Das Archiv lautet scd10en.exe. If you have installed the Microsoft Script Debugger on your machine, you can use this tool for debugging purposes. Then there are two possibilities to debug a script using Microsoft Script Debugger:
- The recommended method in WSH 1 is to put a stop statement into the first lines of a VBScript program. In JS you must use the debugger statement in the code. These statements invoke the script debugger if the statement is executed. Then you may use the debugger to step through your code.
- In WSH 2 you need to invoke your .js and .vbs files using the switches //D or //X. //X invokes the Debugger after the first statement is reached. //D invokes the debugger only, if a stop or debugger statement is reached.
- In .wsf files you can supress debugg by inserting a <? debug="false"> processing instruction into the script file.
Im Command Window kann man dann über WScript.Echo(<Variable>) den Wert dumpen.
Libraries[edit]
Beispiele[edit]
- c:\Uwes\WinScripts\Autostart.js
- c:\Uwes\WinScripts\Access.js
- c:\Uwes\WinScripts\Outlook.js