JavaScript/JScript

From Wiki RB4

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)

  • 1999: ES3
  • 2009: ES5
  • 2015: ES6 (class, constructor, extends, ...)
  • 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

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.

HTML embedding

<script type="text/javascript">
  <javascript code>
</script>

Comments

// einzeilig
/* mehrzeilig */ 

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 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

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") ...

Operatoren

== Value Comparison
=== Value and Type Comparison
&& logical AND
logical OR

Conditional Statements

if (<Expression)
{
  <statements>
}
[else
{
  <statements>
}]

Arrays

Arrays sind Objekte which can contain different objects. Arrays werden durch

var arr = [[( <Number> | <Element> {,<Element>})]];
var arr = new Array([( <Number> | <Element> {,<Element>})]);

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

push()

adds an element at the end

pop()

removes the last element

splice()
splice(i,n)

removes n elements starting at i

shift()

removes the first element

unshift()

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

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

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();

Namespacing

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

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

var x = new <ClassName>(<Ctor Parameter>);

Object Declaration

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

name = person.lastName;
name = person["lastName"];

this

  • 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.

Modules

  • 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

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.

HTML DOM objects

The HTML DOM can be accessed with JavaScript (and with other programming languages). In the DOM, all HTML elements are defined as objects.

document

The document object is the web page.

getElementByID(IDString)

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)

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>)
document.<Formname>.elements[<Index>].(<Methode>|<Eigenschaft>)

Window Object

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
  • document
openWindow()

details see here

Strings

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

<String> + <String>;

Methoden

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

Date

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.

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>

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.


Libraries

Beispiele

  • c:\Uwes\WinScripts\Autostart.js
  • c:\Uwes\WinScripts\Access.js
  • c:\Uwes\WinScripts\Outlook.js

Resources