JavaScript/JScript
Introduction
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). 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. 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
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
JS is case-sensitive language.
Variables
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 when declaring variables that are local to a function. Local variables are those that are only within the function. At all other times, using the var statement to declare variables before their use is a recommended practice. The first character must be a letter (either uppercase or lowercase) or an underscore (_), or a dollar sign ($). 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. Microsoft JScript has six types of data. The main types are numbers, strings, objects, and Booleans. The other two are null and undefined. 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
You can declare a variable implicitly (without using var) by assigning a value to it. You cannot, however, use a variable that has never been declared at all. To do so generates an error at runtime. 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") ...
Operatoren
| == | Comparison |
Conditional Statements
if (<Expression) {\\ <statements>}\\ [ else {\\ <statements>}]
Arrays
Arrays sind Objekte. Arrays werden durch
<ArrayName> = new Array([( <Number> | <Element> {,<Element>})]);
deklariert. Die Indizierung ist 0-based. Arrays haben eine member variable length. Arrays sind immer auch assoziative Arrays. Man kann ein Element einerseits über den Index adressieren oder aber auch über den Namen.
Beispiel:
var x = new Array() x.y = 10; alert(x[0]); alert(x.y); alert(x["y"]);
Um die Namen der Array-Element zu erhalten gibt es folgendes Konstrukt:
for (<Name> in <ArrayName>)
{
alert("Name: " + <Name>);
alert("Wert: " + <ArrayName>[<Name>]);
}
Methoden der Array-Klasse
Die Methode concat() konkateniert zwei Arrays. Die Methode join(<Trennzeichen>) verwandelt einen Array in eine Zeichenkette. Die Methode pop() entfernt das letzte Element eines Arrays. Die Methode push() hängt ein oder mehrere Elemente an das Ende. shift() entfernt das erste Element. slice() schneidet eine gewissen Anzahl aus. splice() fügt ein oder mehrere Elemente an einer bestimmten Postion ein.
Weitere Methoden:
sort() unshift()
Function Definition
Die Definition von Funktionen kann überall im Quellcode erfolgen und muss nicht vor der Verwendung erfolgen.
functionDeclaration := function <FunctionName>(<ParameterList>) {\\ <StatementList>}\\
<ParameterList> := <Name>{,<Name>}
Object Declaration
Die sogenannte object declaration ist im eigentlich Sinn eine class declartion und wirkt sehr merkwürdig. Member heissen bei JS 'property'. Die Schritte sind folgende:
// method declaration function <MethodName>(<ParameterList>) { this.<MemberName> = <ParameterListElement>;...}
// class declaration function <ClassName>(<ParameterList>) { // declaration of a member/propertythis.<MemberName> = <ParameterListElement>; // declaration of a methodthis.<MethodName> = <MethodName>; ...}
// object instantion var <NewVar> = new <ClassName>(<ActualParamterList>);
API
Ausgabe im Internet Explorer
alert((<String>|<Number>))
Beispiel:
alert("");
bewirkt eine Message Box z.B. im IE4 :
\\1.jpg
Ausgaben aus einem klassischen Skript
WScript.Echo(<String>);
predefined Objects
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.
document
Das Objekt document ist vordefiniert.
getElementByID(IDString)
kkj
write(<HTML String>)
The write method can be called only during the loading of the page to insert contents into the parsing of the document.
writeln()
form
document.<Formname>.(<Methode>|<Eigenschaft>)\\ document.forms[<Index>].(<Methode>|<Eigenschaft>)
die folgende Anweisung geht sowohl für IE und NC:\\
document.forms["<Formname>"].(<Methode>|<Eigenschaft>)
Elemente von forms
document.<Formname>.elements[<Index>].(<Methode>|<Eigenschaft>)
die folgende Anweisung geht sowohl für IE als auch NC:\\
document.forms["<Formname>"].elements["<ElementName>"].(<Methode>|<Eigenschaft>)
der folgende Ausdruck sollte eigentlich funktionieren, tut es aber nicht:\\
document.<Formname>.<ElementName>.(<Methode>|<Eigenschaft>)\\
\\
Eigenschaften
checked defaultChecked defaultValue form name type value
Methoden
blur() click() focus() handleEvent() select()
Unterobjekte
options
Strings
var x = new String(""); // new String Object var y = ""; // new String Literal var z = ;
Konkatenation
<String> + <String>;
Methoden
| Array split(<Seperator>[,MaxSplits]) | ||
| String replace(<RegExpression>,<ReplaceWith>) | returns a new String Object |
Date
Tips
Skript beenden
WScript.Quit();
Andere Seite laden
window.location.href = "<URL>";
Seite in anderem Fenster laden
window.open(<URL>,<TITLE>,width=, height=, resizeable=)
Fokus setzen
document.<FormName>.<ElementName>.focus();
CheckBox in einer Form prüfen
document.forms["TestForm"].elements"TestCheckbox".checked
Bei Selektion in Select etwas tun
<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>
Dateien kopieren
s. 1
Excel steuern
Das OLE-Automation Objektmodell schaut man sich am besten in der VBA-Entwicklungsumgebung an. s. 1
Access steuern
Das Access-Objektmodell schaut man sich am besten in einer VBA Entwicklungsumgebung an, nachdem man die Type-Library eingebunden hat (s. 2).
Outlook steuern
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
Microsoft Script Debugger
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.
Beispiele
- c:\Uwes\WinScripts\Autostart.js
- c:\Uwes\WinScripts\Access.js
- c:\Uwes\WinScripts\Outlook.js