What Is JScript?
Table of Contents
What Is JScript?.................................................................................................................................................1
Using JScript............................................................................................................................................1
JScript Variables.................................................................................................................................................1
Declaring Variables.................................................................................................................................1
Naming Variables....................................................................................................................................1
Coercion...................................................................................................................................................2
JScript Operators................................................................................................................................................1
Computational Operators.........................................................................................................................1
Logical Operators..............................................................................................................................1
JScript Objects....................................................................................................................................................1
Objects as Arrays.....................................................................................................................................1
Recursion.............................................................................................................................................................1
Variable Scope.....................................................................................................................................................1
i
What Is JScript?
Table of Contents
Copying, Passing, and Comparing Data...........................................................................................................1
By Value vs. By Reference......................................................................................................................1
Passing Parameters to Functions..............................................................................................................1
Testing Data.............................................................................................................................................2
Special Characters..............................................................................................................................................1
abs Method..........................................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
acos Method.........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
anchor Method....................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
asin Method.........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
atan Method.........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
atan2 Method.......................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
big Method...........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
ii
What Is JScript?
Table of Contents
blink Method.......................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
bold Method.........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
ceil Method..........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
charAt Method....................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
compile Method...................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
cos Method...........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
dimensions Method.............................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................2
escape Method.....................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
eval Method.........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
exec Method.........................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
exp Method..........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
iii
What Is JScript?
Table of Contents
fixed Method........................................................................................................................................................1
The required strVariable reference is any String object or literal............................................................1
Remarks.............................................................................................................................................1
floor Method........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
fontcolor Method.................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
fontsize Method...................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
getDate Method...................................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
getDay Method....................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
getHours Method................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
getMinutes Method.............................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
getMonth Method................................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
getSeconds Method.............................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
getTime Method..................................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
getTimezoneOffset Method................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
getVarDate Method............................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
iv
What Is JScript?
Table of Contents
getYear Method...................................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
indexOf Method..................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
italics Method......................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
item Method.........................................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
join Method..........................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
lastIndexOf Method............................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
lbound Method....................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
link Method..........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
log Method...........................................................................................................................................................1
Return Value............................................................................................................................................1
Requirements.....................................................................................................................................1
match Method......................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
max Method.........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
min Method..........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
parse Method.......................................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
v
What Is JScript?
Table of Contents
parseFloat Method..............................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
parseInt Method..................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
pow Method.........................................................................................................................................................1
Arguments................................................................................................................................................1
Example.............................................................................................................................................1
random Method...................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
replace Method....................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
reverse Method....................................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
round Method......................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
search Method.....................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
setDate Method....................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
setHours Method.................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
setMonth Method................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
setSeconds Method..............................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
setTime Method...................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
vi
What Is JScript?
Table of Contents
setYear Method...................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
sin Method...........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
small Method.......................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
sort Method..........................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
split Method.........................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
sqrt Method.........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
strike Method......................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
sub Method..........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
substr Method......................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
substring Method................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
sup Method..........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
vii
What Is JScript?
Table of Contents
tan Method...........................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
test Method..........................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
toGMTString Method.........................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
toLocaleString Method.......................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
toLowerCase Method..........................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
toUpperCase Method..........................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
ubound Method...................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
unescape Method.................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
Array Object........................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
arguments Object................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
Date Object..........................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
Global Object......................................................................................................................................................1
Remarks...................................................................................................................................................1
Properties...........................................................................................................................................1
Math Object.........................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
viii
What Is JScript?
Table of Contents
Regular Expression Object................................................................................................................................1
Syntax 1...................................................................................................................................................1
Syntax 2.............................................................................................................................................1
String Object.......................................................................................................................................................1
Syntax......................................................................................................................................................1
Arguments.........................................................................................................................................1
ix
What Is JScript?
Table of Contents
Comparison Operators.......................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
delete Operator....................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
instanceof Operator............................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
new Operator.......................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
x
What Is JScript?
Table of Contents
Subtraction Assignment Operator (-=).............................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
typeof Operator...................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
void Operator......................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
0...n Properties.....................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
$1...$9 Properties.................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
callee Property.....................................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
constructor Property..........................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
E Property............................................................................................................................................................1
Requirements...........................................................................................................................................1
See Also.............................................................................................................................................1
index Property.....................................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
xi
What Is JScript?
Table of Contents
length Property (Array).....................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
LN10 Property.....................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
LN2 Property.......................................................................................................................................................1
Syntax......................................................................................................................................................1
Requirements.....................................................................................................................................1
LOG10E Property...............................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
LOG2E Property.................................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
PI Property..........................................................................................................................................................1
Syntax......................................................................................................................................................1
Requirements.....................................................................................................................................1
prototype Property..............................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
source Property...................................................................................................................................................1
Requirements...........................................................................................................................................1
See Also.............................................................................................................................................1
SQRT1_2 Property.............................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
SQRT2 Property.................................................................................................................................................1
Syntax......................................................................................................................................................1
Requirements.....................................................................................................................................1
undefined Property.............................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
xii
What Is JScript?
Table of Contents
@cc_on Statement...............................................................................................................................................1
Remarks...................................................................................................................................................1
Requirements.....................................................................................................................................1
@if Statement......................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
@set Statement....................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
break Statement..................................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
Comment Statements..........................................................................................................................................1
Syntax 1...................................................................................................................................................1
Syntax 2.............................................................................................................................................1
continue Statement..............................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
do...while Statement............................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
for Statement.......................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
for...in Statement.................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
function Statement..............................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
if...else Statement.................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
Labeled Statement..............................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
return Statement.................................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
xiii
What Is JScript?
Table of Contents
switch Statement.................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
this Statement......................................................................................................................................................1
Remarks...................................................................................................................................................1
Example.............................................................................................................................................1
try...catch
finally Statement..............................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
var Statement......................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
while Statement...................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
with Statement.....................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
Count Property....................................................................................................................................................1
Remarks...................................................................................................................................................1
See Also.............................................................................................................................................1
Item Property......................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
xiv
What Is JScript?
Table of Contents
Key Property.......................................................................................................................................................1
Arguments................................................................................................................................................1
Remarks.............................................................................................................................................1
Column Property................................................................................................................................................1
Remarks...................................................................................................................................................1
See Also.............................................................................................................................................1
Line Property......................................................................................................................................................1
Remarks...................................................................................................................................................1
See Also.............................................................................................................................................1
Count Property....................................................................................................................................................1
Remarks...................................................................................................................................................1
See Also.............................................................................................................................................1
Script Components..............................................................................................................................................1
Exposing Methods...............................................................................................................................................1
See Also...................................................................................................................................................2
Exposing Properties............................................................................................................................................1
See Also...................................................................................................................................................3
xv
What Is JScript?
Table of Contents
Exposing Events..................................................................................................................................................1
Declaring Events......................................................................................................................................1
Specifying Dispatch Identifiers................................................................................................................1
Firing an Event.........................................................................................................................................2
See Also.............................................................................................................................................2
xvi
What Is JScript?
Table of Contents
<implements> Element.......................................................................................................................................1
Values......................................................................................................................................................1
Remarks.............................................................................................................................................1
<property> Element............................................................................................................................................1
Values......................................................................................................................................................1
Remarks.............................................................................................................................................1
<public> Element................................................................................................................................................1
See Also...................................................................................................................................................1
<reference> Element...........................................................................................................................................1
Values......................................................................................................................................................1
Remarks.............................................................................................................................................1
<registration> Element.......................................................................................................................................1
Values......................................................................................................................................................1
Remarks.............................................................................................................................................1
<resource> Element............................................................................................................................................1
Values......................................................................................................................................................1
Remarks.............................................................................................................................................1
<script> Element.................................................................................................................................................1
Values......................................................................................................................................................1
Remarks.............................................................................................................................................1
<component> Element........................................................................................................................................1
Values......................................................................................................................................................1
Remarks.............................................................................................................................................1
<attach> Element................................................................................................................................................1
Values......................................................................................................................................................1
Example.............................................................................................................................................1
element Property.................................................................................................................................................1
Values......................................................................................................................................................1
Remarks.............................................................................................................................................1
<layout> Element................................................................................................................................................1
Values......................................................................................................................................................1
Remarks.............................................................................................................................................1
xvii
What Is JScript?
xviii
What Is JScript?
JScript is the Microsoft implementation of the ECMA 262 language specification (ECMAScript Edition 3).
With only a few minor exceptions (to maintain backwards compatibility), JScript is a full implementation of
the ECMA standard. This overview is intended to help you get started with JScript.
Using JScript
JScript is an interpreted, object-based scripting language. Although it has fewer capabilities than full-fledged
object-oriented languages like C++, JScript is more than sufficiently powerful for its intended purposes.
JScript is not a cut-down version of another language (it is only distantly and indirectly related to Java, for
example), nor is it a simplification of anything. It is, however, limited. You cannot write stand-alone
applications in it, for example, and it has no built-in support for reading or writing files. Moreover, JScript
scripts can run only in the presence of an interpreter or "host", such as Active Server Pages (ASP), Internet
Explorer, or Windows Script Host.
JScript is a loosely typed language. Loosely typed means you do not have to declare the data types of
variables explicitly. In fact, JScript takes it one step further. You cannot explicitly declare data types in
JScript. Moreover, in many cases JScript performs conversions automatically when needed. For instance, if
you add a number to an item consisting of text (a string), the number is converted to text.
The rest of this user's guide is an overview of JScript features. For full details of the language implementation,
consult the language reference.
Note The code in many of the following examples is somewhat more explicit and less dense
than code you are likely to find in actual Web pages. The intent here is to clarify the concepts,
not to express optimal coding conciseness and style. In any case, there is no shame in writing
code that you can read and easily understand six months after you write it.
JScript
What Is JScript? 1
2 What Is JScript?
2 What Is JScript?
Writing JScript Code
Like many other programming languages, Microsoft JScript is written in text format, and organized into
statements, blocks consisting of related sets of statements, and comments. Within a statement you can use
variables, immediate data such as strings and numbers (called "literals"), and expressions.
Statements
A JScript program is a collection of statements. A JScript statement is equivalent to a complete sentence in
English. JScript statements combine expressions in such a way that they carry out one complete task.
A statement consists of one or more expressions, keywords, or operators (symbols). Typically, a statement is
written on a single line, although a statement can be written over two or more lines. Also, two or more
statements can be written on the same line by separating them with semicolons. In general, each new line
begins a new statement. It is a good idea to terminate your statements explicitly. You do this with the
semicolon (;), which is the JScript statement termination character. Here are two examples of JScript
statements.
A group of JScript statements surrounded by braces ({}) is called a block. Statements grouped into a block
can generally be treated as a single statement. This means you can use blocks in most places that JScript
expects a lone statement. Notable exceptions include the headers of for and while loops. Notice that the
primitive statements within a block end in semicolons, but the block itself does not.
Generally, blocks are used in functions and conditionals. Notice that unlike C++ and some other languages,
JScript does not consider a block to be a new scope; only functions create a new scope. In the following
example, the first statement begins the definition of a function that consists of a block of five statements.
Following the block are three statements that are not surrounded by braces; these statements are not a block,
and are therefore not part of the function definition.
function convert(inches) {
feet = inches / 12; // These five statements are in a block.
miles = feet / 5280;
nauticalMiles = feet / 6080;
cm = inches * 2.54;
meters = inches / 39.37;
}
km = meters / 1000; // These three statements are not in a block.
kradius = km;
mradius = miles;
Comments
A single-line JScript comment begins with a pair of forward slashes (//). Here is an example of a single line
comment.
A multiline JScript comment begins with a forward slash and asterisk (/*), and ends with the reverse (*/).
/*
This is a multiline comment that explains the preceding code statement.
Note If you attempt to embed one multiline comment within another, JScript interprets the
resulting multiline comment in an unexpected way. The */ that marks the end of the
embedded multiline comment is interpreted as the end of the whole multiline comment. This
means that the text that follows the embedded multiline comment will not be commented out;
instead, it will be interpreted as JScript code, and will generate syntax errors.
It is recommended that you write all your comments as blocks of single-line comments. This allows you to
comment out large segments of code with a multiline comment later.
var extendedIdea = aGoodIdea + " You never know when you'll have to figure out what it does.";
• variables,
• array elements,
• object properties.
The right operand of the = operator is always an Rvalue. Rvalues can be an arbitrary value of any type,
including the value of an expression. Here is an example of a JScript assignment statement.
anInteger = 3;
The JScript compiler interprets this statement as meaning: "Assign the value 3 to the variable anInteger," or
"anInteger takes the value 3."
Be certain you understand the difference between the = operator (assignment) and the == operator (equality).
When you want to compare two values to find out if they are equal, use two equals sings (==). This is
discussed in detail in Controlling Program Flow.
Expressions
A JScript expression is a 'phrase' of JScript that a JScript interpreter can evaluate to generate a value. The
value can be of any valid JScript type - a number, a string, an object, and so on. The simplest expressions are
literals. Here are some examples of JScript literal expressions.
More complicated expressions can contain variables, function calls, and other expressions. You can combine
expressions to create complex expressions using operators. Examples of operators are:
+ // additon
- // subtraction
* // multiplication
/ // division
var anExpression = 3 * (4 / 5) + 6;
var aSecondExpression = Math.PI * radius * radius;
var aThirdExpression = aSecondExpression + "%" + anExpression;
var aFourthExpression = "(" + aSecondExpression + ") % (" + anExpression + ")";
JScript
How old am I?
In JScript, a variable is the name you give that concept; it represents the value at a given instant. When you
use the variable, you really mean the data it represents. Here is an example:
In a mechanical sense, you use variables to store, retrieve, and manipulate all the different values that appear
in your scripts. Always create a meaningful variable name; that makes it easy for humans to understand what
your scripts do.
Declaring Variables
The first time a variable appears in your script is its declaration. This first mention of the variable sets it up in
memory so you can refer to it later on in your script. Always declare variables before using them. You do this
using the var keyword.
If you do not initialize your variable in the var statement, it automatically takes on the JScript value
undefined. Although it is unsafe to do so, it is legal JScript syntax to omit the var keyword from your
declaration statement. When you do, the JScript interpreter gives the variable global scope visibility. When
you declare a variable at the procedure level though, you do not want it to be visible at the global scope; in
this case, you must use the var keyword in your variable declaration.
Naming Variables
A variable name is an identifier. In JScript, identifiers are used to:
• name variables,
• name functions,
• provide labels for loops.
JScript is a case-sensitive language. This means a variable name such as myCounter is different than the
variable name MYCounter. Variable names can be of any length. The rules for creating legal variable names
are as follows:
• The first character must be an ASCII letter (either uppercase or lowercase), or an underscore (_)
character. Note that a number cannot be used as the first character.
• Subsequent characters must be letters, numbers, or underscores.
• The variable name must not be a reserved word.
_pagecount
Part9
Number_Items
JScript Variables 1
2 JScript Variables
When you want to declare a variable and initialize it, but do not want to give it any particular value, assign it
the JScript value null. Here is an example.
If you declare a variable without assigning a value to it, it exists, but has the JScript value undefined. Here is
an example.
var currentCount;
var finalCount = 1 * currentCount; // finalCount has the value NaN since currentCount is undefined.
Note that the main difference between null and undefined in JScript is that null behaves like the number 0,
while undefined behaves like the special value NaN (Not a Number). A null value and an undefined value
will always compare to be equal.
You can declare a variable without using the var keyword in the declaration, and assign a value to it. This is
an implicit declaration.
var volume = length * width; // Error - length and width do not yet exist.
Coercion
The JScript interpreter can only evaluate expressions in which the data types of the operands are the same.
Without coercion, an expression that attempts to perform an operation on two different data types (a number
and a string for example) would produce an erroneous result. But that is not the case with JScript.
JScript is a loosely typed language. This means its variables have no predetermined type (as opposed to
strongly typed languages like C++). Instead, JScript variables have a type that corresponds to the type of value
they contain. A benefit of this behavior is that it provides you with the flexibility to treat a value as if it were
of another type.
In JScript, you can perform operations on values of differing types without fear that the JScript interpreter will
raise an exception. Instead, the JScript interpreter automatically changes (coerces) one of the data types to that
of the other, then performs the operation. For example:
Operation Result
Add a number and a string The number is coerced into a string.
Add a Boolean and a string The Boolean is coerced into a string.
Add a number and a Boolean The Boolean is coerced into a number.
Consider the following example.
2 JScript Variables
JScript Variables 3
To explicitly convert a string to an integer, use the parseInt Method. To explicitly convert a string to a
number, use the parseFloat Method. Notice that strings are automatically converted to equivalent numbers for
comparison purposes, but are left as strings for addition (concatenation).
JScript
JScript Variables 3
4 JScript Variables
4 JScript Variables
JScript Data Types
In JScript, there are three primary data types, two composite data types, and two special data types.
• String
• Number
• Boolean
• Object
• Array
• Null
• Undefined
Notice that JScript does not have a type to represent a single character. To represent a single character in
JScript, you create a string that consists of only one character. A string that contains zero characters ("") is an
empty (zero-length) string.
Integer Values
Integer values can be positive whole numbers, negative whole numbers, and 0. They can be represented in
base 10 (decimal), base 8 (octal), and base 16 (hexadecimal). Most numbers in JScript are written in decimal.
You denote octal integers by prefixing them with a leading "0" (zero). They can contain digits 0 through 7
only. A number with a leading "0", containing the digits "8" and/or "9" is interpreted as a decimal number.
You denote hexadecimal ("hex") integers by prefixing them with a leading "0x" (zero and x|X). They can
contain digits 0 through 9, and letters A through F (either uppercase or lowercase) only. The letters A through
F are used to represent, as single digits, 10 through 15 in base 10. That is, 0xF is equivalent to 15, and 0x10 is
equivalent to 16.
Floating-point Values
Floating-point values can be whole numbers with a decimal portion. Additionally, they can be expressed in
scientific notation. That is, an uppercase or lowercase "e" is used to represent "ten to the power of". JScript
represents numbers using the eight byte IEEE 754 floating-point standard for numerical representation. This
means you can write numbers as large as ±1.7976931348623157x10308, and as small as ±5x10-324. A number
that begins with a single "0" and contains a decimal point is interpreted as a decimal floating-point number.
Notice that a number that begins with "0x" or "00" and contains a decimal point will generate an error. Here
are some examples of JScript numbers.
• NaN (not a number). This is used when a mathematical operation is performed on inappropriate data,
such as strings or the undefined value
• Positive Infinity. This is used when a positive number is too large to represent in JScript
• Negative Infinity. This is used when a negative number is too large to represent in JScript
• Positive and Negative 0. JScript differentiates between positive and negative zero.
Comparisons you make in your scripts always have a Boolean outcome. Consider the following line of JScript
code.
y = (x == 2000);
Here, the value of the variable x is tested to see if it is equal to the number 2000. If it is, the result of the
comparison is the Boolean value true, which is assigned to the variable y. If x is not equal to 2000, then the
result of the comparison is the Boolean value false.
Boolean values are especially useful in control structures. Here, you combine a comparison that creates a
Boolean value directly with a statement that uses it. Consider the following JScript code sample.
if (x == 2000)
z = z + 1;
else
x = x + 1;
The if/else statement in JScript performs one action if a Boolean value is true (in this case, z = z + 1), and an
alternate action if the Boolean value is false (x = x + 1).
You can use any expression as a comparative expression. Any expression that evaluates to 0, null, undefined,
or an empty string is interpreted as false. An expression that evaluates to any other value is interpreted as
true. For example, you could use an expression such as:
Note that the above line does not check if x is equal to y + z, since only a single equal sign (assignment) is
used. Instead, the code above assigns the value of y + z to the variable x, and then checks if the result of the
entire expression (the value of x) is zero. To check if x is equal to y + z, use the following code.
A variable that contains null contains "no value" or "no object." In other words, it holds no valid number,
string, Boolean, array, or object. You can erase the contents of a variable (without deleting the variable) by
assigning it the null value.
Notice that in JScript, null is not the same as 0 (as it is in C and C++). Also note that the typeof operator in
JScript will report null values as being of type Object, not of type null. This potentially confusing behavior is
for backwards compatibility.
Notice that you cannot test to see if a variable exists by comparing it to undefined, although you can check if
its type is "undefined". In the following code example, assume that the programmer is trying to test if the
variable x has been declared:
someObject.prop == null;
To check if an object property exists, you can use the new in operator:
if ("prop" in someObject)
// someObject has the property 'prop'
JScript
Computational Operators
Description Symbol
Unary negation -
Increment ++
Decrement
Multiplication *
Division /
Modulus arithmetic %
Addition +
Subtraction -
Logical Operators
Description Symbol
Logical NOT !
Less than <
Greater than >
Less than or equal to <=
Greater than or equal to >=
Equality ==
Inequality !=
Logical AND &&
Logical OR ||
Conditional (ternary) ?:
Comma ,
Strict Equality ===
Strict Inequality !==
Bitwise Operators
Description Symbol
Bitwise NOT ~
Bitwise Left Shift <<
Bitwise Right Shift >>
Unsigned Right Shift >>>
Bitwise AND &
Bitwise XOR ^
Bitwise OR |
Assignment Operators
Description Symbol
Assignment =
JScript Operators 1
2 JScript Operators
Description Symbol
delete delete
typeof typeof
void void
instanceof instanceof
new new
in in
The difference between == (equality) and === (strict equality) is that the equality operator will coerce values
of different types before checking for equality. For example, comparing the string "1" with the number 1 will
compare as true. The strict equlity operator, on the other hand, will not coerce values to different types, and so
the string "1" will not compare as equal to the number 1.
Primitive strings, numbers, and Booleans are compared by value. If they have the same value, they will
compare as equal. Objects (including Array, Function, String, Number, Boolean, Error, Date and RegExp
objects) compare by reference. Even if two variables of these types have the same value, they will only
compare as true if they refer to exactly the same object.
For example:
JScript
2 JScript Operators
Controlling Program Flow
Normally, statements in a JScript script are executed one after the other, in the order in which they are written.
This is called sequential execution, and is the default direction of program flow.
An alternative to sequential execution transfers the program flow to another part of your script. That is,
instead of executing the next statement in the sequence, another statement is executed instead.
To make a script useful, this transfer of control must be done in a logical manner. Transfer of program control
is based upon a decision, the result of which is a truth statement (returning a Boolean true or false). You
create an expression, then test whether its result is true. There are two main kinds of program structures that
accomplish this.
The first is the selection structure. You use it to specify alternate courses of program flow, creating a junction
in your program (like a fork in a road). There are four selection structures available in JScript.
The second type of program control structure is the repetition structure. You use it to specify that an action is
to be repeated while some condition remains true. When the conditions of the control statement have been met
(usually after some specific number of iterations), control passes to the next statement beyond the repetition
structure. There are four repetition structures available in JScript.
You can create quite complex scripts by nesting and stacking selection and repetition control structures.
A third form of structured program flow is provided by exception handling, which is not covered in this
document.
The following examples demonstrate syntaxes you can use with if and if...else statements. The first example
shows the simplest kind of Boolean test. If (and only if) the item between the parentheses evaluates to (or can
be coerced to) true, the statement or block of statements after the if is executed.
// In this example, the test fails unless both conditions are true.
if (rind.color == "deep yellow " && rind.texture == "large and small wrinkles")
{
Conditional Operator
JScript also supports an implicit conditional form. It uses a question mark after the condition to be tested
(rather than the word if before the condition). It also specifies two alternatives, one to be used if the condition
is met and one if it is not. A colon must separate these alternatives.
If you have several conditions to be tested together, and you know that one is more likely to pass or fail than
the others, you can use a feature called 'short circuit evaluation' to speed the execution of your script. When
JScript evaluates a logical expression, it only evaluates as many sub-expressions as required to get a result.
For example, if you have andAnd' expression such as ((x == 123) && (y == 42)), JScript first checks if x is
123. If it is not, the entire expression cannot be true, even if y is equal to 42. Hence, the test for y is never
made, and JScript returns the value false.
Similarly, if only one of several conditions must be true (using the || operator), testing stops as soon as any
one condition passes the test. This is effective if the conditions to be tested involve the execution of function
calls or other complex expressions. With this in mind, when you write Or expressions, place the conditions
most likely to be true first. When you write And expressions, place the conditions most likely to be false first.
A benefit of designing your script in this manner is that runsecond() will not be executed in the following
example if runfirst() returns 0 or false.
Using Loops
There are several ways to execute a statement or block of statements repeatedly. In general, repetitive
execution is called looping or iteration. An iteration is simply a single execution of a loop. It is typically
controlled by a test of a variable, where the value of which is changed each time the loop is executed. JScript
supports four types of loops: for loops, for...in loops, while loops, do...while loops.
If the condition for looping is never met, the loop is never executed. If the test condition is always met, an
infinite loop results. While the former may be desirable in certain cases, the latter rarely is, so be cautious
when writing your loop conditions.
/*
The update expression ("icount++" in the following examples)
is executed at the end of the loop, after the block of statements that forms the
body of the loop is executed, and before the condition is tested.
*/
var sum = new Array(howFar); // Creates an array called sum with 10 members, 0 through 9.
var theSum = 0;
sum[0] = 0;
for(var icount = 0; icount < howFar; icount++) { // Counts from 0 through 9 in this case.
theSum += icount;
sum[icount] = theSum;
}
var newSum = 0;
for(var icount = 0; icount > howFar; icount++) { // This isn't executed at all, since icount is n
newSum += icount;
}
var sum = 0;
for(var icount = 0; icount >= 0; icount++) { // This is an infinite loop.
sum += icount;
}
The following code sample should be run from within Internet Explorer, since it uses the alert method, which
is not a part of JScript.
var x = 0;
while ((x != 42) && (x != null))
{
x = window.prompt("What is my favourite number?", x);
}
if (x == null)
window.alert("You gave up!");
else
window.alert("Yep - it's the Ultimate Answer!");
Note Because while loops do not have explicit built-in counter variables, they are more
vulnerable to infinite looping than the other types of loops. Moreover, because it is not
necessarily easy to discover where or when the loop condition is updated, it is easy to write a
while loop in which the condition never gets updated. For this reason, you should be careful
when you design while loops.
As noted above, there is also a do...while loop in JScript that is similar to the while loop, except that it is
guaranteed to always execute at least once, since the condition is tested at the end of the loop, rather than at
the start. For example, the loop above can be re-written as:
var x = 0;
do
{
x = window.prompt("What is my favourite number?", x);
} while ((x != 42) && (x != null));
if (x == null)
window.alert("You gave up!");
else
window.alert("Yep - it's the Ultimate Answer!");
The following example builds on the previous example to use the break and continue statements to control
the loop.
var x = 0;
do
{
} while (x != 42)
if (x == null)
window.alert("You gave up!");
else
window.alert("Yep - it's the Ultimate Answer!");
JScript
Objects as Arrays
In JScript, objects and arrays are handled almost identically. Both can have arbitrary properties assigned to
them, and indeed Arrays are merely a special kind of Object. The difference between Arrays and Objects is
that arrays have a "magic" length property, whilst objects do not. This means that if you assign a value to an
element of an array that is greater than every other element for example, myArray[100] = "hello" then
the length property will automatically be updated to be 101 (the new length). Similarly, if you modify the
length property of an array, it will delete any elements that are no longer part of the array.
All objects in JScript support "expando" properties, or properties that can be added and removed dynamically
at run time. These properties can have any name, including numbers. If the name of the property is a simple
identifier<<ref for identifier rules>>, it can be written after the object name with a period, such as:
If the name of the property is not a simple identifier, or it is not known at the time you write the script, you
can use an arbitrary expression inside square brackets to index the property. The names of all expando
properties in JScript are converted to strings before being added to the object.
Traditionally, array elements are given numeric indices, starting at zero. It is these elements that interact with
the length property. Nevertheless, because all arrays are also objects, they support expando properties as well.
Note, though, that expando properties do not interact with the length property in any way. For example:
JScript Objects 1
2 JScript Objects
myArray["another Expando"] = "Windows";
Although JScript does not directly support multi-dimensional arrays, you can store any sort of data inside
array elements including other arrays. So you can get the behavior of multi-dimensional arrays by storing
arrays within the elements of another array. For example, the following code builds a multiplication table for
the numbers up to 5:
window.alert(MultiplicationTable[3][4]); // Displays 12
window.alert(MultiplicationTable[5][2]); // Displays 10
window.alert(MultiplicationTable[1][4]); // Displays 4
JScript
2 JScript Objects
JScript Reserved Words
JScript has a number of reserved words that you cannot use as identifiers. Reserved words have a specific
meaning to the JScript language, as they are part of the language syntax. Using a reserved word causes a
compilation error when loading your script.
JScript also has a list of future reserved words. These words are not currently part of the JScript language,
although they are reserved for future use.
Reserved Words
JScript
The constructor is passed a reference to a newly created empty object as the value of the special this keyword.
It is then responsible for performing appropriate initialization for the new object (creating properties and
giving them initial values). When completed, the constructor returns a reference to the object it constructed.
Writing Constructors
You can create objects and initialize them using the new operator in conjunction with predefined constructor
functions such as Object(), Date(), and Function(). A powerful feature of object-oriented programming is the
ability to define custom constructor functions to create custom objects for use in your scripts. You create
custom constructors so you can create objects with properties already defined. Here is an example of a custom
constructor (note the use of the this keyword).
When you invoke the Circle constructor, you supply values for the circle's center point and the radius (these
elements are all that is needed to completely define a unique circle object). You end up with a Circle object
that contains three properties. Here is how you would instantiate a Circle object.
Circle.prototype.pi = Math.PI;
function ACirclesArea () {
return this.pi * this.r * this.r; // The formula for the area of a circle is Ïr2.
}
Circle.prototype.area = ACirclesArea; // The function that calculates the area of a circle is now
var a = ACircle.area(); // This is how you would invoke the area function on a Circ
Using this principle, you can define additional properties for predefined constructor functions (which all have
prototype objects). For example, if you want to be able to remove leading and trailing spaces from strings
(similar to VBScript's Trim function), you can create your own method on the String prototype object, and
all strings in your script will automatically inherit the method.
JScript
"If the number is less than zero, reject it. If it is not an integer, round it down to the next integer. If the number
is zero, its factorial is one. If the number is larger than zero, multiply it by the factorial of the next lesser
number."
To calculate the factorial of any number that is larger than zero, you need to calculate the factorial of at least
one other number. The function you use to do that is the function you're in the middle of already; the function
must call itself for the next smaller number, before it can execute on the current number. This is an example of
recursion.
Recursion and iteration (looping) are strongly related - anything that can be done with recursion can be done
with iteration, and vice-versa. Usually a particular computation will lend itself to one technique or the other,
and you simply need to choose the most natural approach, or the one you feel most comfortable with.
Clearly, there is a way to get in trouble here. You can easily create a recursive function that does not ever get
to a definite result, and cannot reach an endpoint. Such a recursion causes the computer to execute a so-called
"infinite" loop. Here's an example: omit the first rule (the one about negative numbers) from the verbal
description of calculating a factorial, and try to calculate the factorial of any negative number. This fails,
because in order to calculate the factorial of, say, -24 you first have to calculate the factorial of -25; but in
order to do that you first have to calculate the factorial of -26; and so on. Obviously, this never reaches a
stopping place.
Thus, it is extremely important to design recursive functions with great care. If you even suspect that there is
any chance of an infinite recursion, you can have the function count the number of times it calls itself. If the
function calls itself too many times (whatever number you decide that should be) it automatically quits.
Here is the factorial function again, this time written in JScript code.
Recursion 1
2 Recursion
JScript
2 Recursion
Variable Scope
JScript has two scopes: global and local. If you declare a variable outside of any function definition, it is a
global variable, and its value is accessible and modifiable throughout your program. If you declare a variable
inside of a function definition, that variable is local. It is created and destroyed every time the function is
executed; it cannot be accessed by anything outside the function.
Languages such as C++ also have "block scope." Here, any set of braces "{}" defines a new scope. JScript
does not support block scopes.
A local variable can have the same name as a global variable, but it is entirely distinct and separate.
Consequently, changing the value of one variable has no effect on the other. Inside the function in which the
local variable is declared, only the local version has meaning.
/*
Within the function, the variable contains "A centaur is probably a mounted Scythian warrior,
misreported; that is, "; outside the function, the variable contains the rest of the sentence:
"a horse with rider, as seen from a distance by a naive innocent."
*/
It's important to note that variables act as if they were declared at the beginning of whatever scope they exist
in. Sometimes this results in unexpected behaviors.
tweak();
var aNumber = 100;
function tweak() {
var newThing = 0; // Explicit declaration of the newThing variable.
// This statement assigns the value undefined to newThing because there is a local variable w
newThing = aNumber;
// The next statement assigns the value 42 to the local aNumberaNumber = 42;
if (false) {
var aNumber; // This statement is never executed.
aNumber = 123; // This statement is never executed.
} // End of the conditional.
When JScript executes a function, it first looks for all variable declarations,
var someVariable;
Variable Scope 1
2 Variable Scope
and creates the variables with an initial value of undefined. If a variable is declared with a value,
then it still initially has the value undefined, and will take on the declared value only when the line containing
the declaration is executed, if ever.
JScript processes variable declarations before executing any code, so it does not matter whether the
declaration is inside a conditional block or some other construct. Once JScript has found all the variables, it
executes the code in the function. If a variable is implicitly declared inside a function - that is, if it appears on
the left-hand-side of an assignment expression but has not been declared with var - then it is created as a
global variable.
JScript
2 Variable Scope
Copying, Passing, and Comparing Data
In JScript, how data is handled depends on its data type.
Objects, arrays, and functions are copied, passed, and compared by reference. When you copy or pass by
reference, you essentially create a pointer to the original item, and use the pointer as if it were a copy. If you
then change the original, you change both the original and the copy (and vice versa). There is really only one
entity; the "copy" is not actually a copy, it's just another reference to the data.
When comparing by reference, the two variables must refer to exactly the same entity for the comparison to
succeed. For example, two distinct Array objects will always compare as unequal, even if they contain the
same elements. One of the variables must be a reference to the other one for the comparison to succeed. To
check if two Arrays hold the same elements, compare the results of the toString() method.
Last, strings are copied and passed by reference, but are compared by value. Note that if you have two String
objects (created with new String("something")), they are compared by reference, but if one or both of the
values is a string value, they are compared by value.
Note Because of the way the ASCII and ANSI character sets are constructed, capital letters
precede lowercase ones in sequence order. For example, "Zoo" compares as less than
"aardvark." You can call toUpperCase() or toLowerCase() on both strings if you want to
perform a case-insensitive match.
Testing Data
When you perform a test by value, you compare two distinct items to see whether they are equal to each other.
Usually, this comparison is performed on a byte-by-byte basis. When you test by reference, you are checking
to see whether two items are pointers to a single original item. If they are, then they compare as equal; if not,
even if they contain the exact same values, byte-for-byte, they compare as unequal.
Copying and passing strings by reference saves memory; but because you cannot change strings once they are
created, it becomes possible to compare them by value. This lets you test whether two strings have the same
content even if one was generated entirely separately from the other.
JScript
JScript
Special Characters 1
2 Special Characters
2 Special Characters
Troubleshooting Your Scripts
There are places in any programming language where you can get caught if you are not careful, and every
language has specific surprises in it. Take, for example, the null value: The one in JScript behaves differently
than the Null value in the C or C++ languages.
Here are some of the trouble areas that you may run into as you write JScript scripts.
Syntax Errors
Because syntax is much more rigid in programming languages than in natural languages, it is important to pay
strict attention to detail when you write scripts. If, for example, you mean for a particular parameter to be a
string, you will run into trouble if you forget to enclose it in quotation marks when you type it.
Note This behavior is specific to Internet Explorer. ASP and WSH have different execution
models (as would other hosts).
"100" == 100;
false == 0;
To check that both the type and value are the same, use the strict equality operator, ===. the following both
evaluate to false:
Operator Precedence
When a particular operation is performed during the evaluation of an expression has more to do with operator
precedence than with the location of the expression. Thus, in the following example, multiplication is
performed before subtraction, even though the subtraction appears first in the expression.
with Keyword
The with statement is convenient for addressing properties that already exist in a specified object, but cannot
be used to add properties to an object. To create new properties in an object, you must refer to the object
specifically.
this Keyword
Although you use the this keyword inside the definition of an object, to refer to the object itself, you cannot
ordinarily use this or similar keywords to refer to the currently executing function when that function is not an
object definition. You can, if the function is to be assigned to an object as a method, use the this keyword
within the function, to refer to the object.
JScript
Category Feature/Keyword
Array Handling Array
join, length, reverse, sort
Assignments Assign (=)
Compound Assign (OP=)
Booleans Boolean
Comments /*...*/ or //
Constants/Literals NaN
null
true, false
Infinity
undefined
Control flow Break
continue
for
for...in
if...else
return
while
Dates and Time Date
getDate, getDay, getFullYear, getHours, getMilliseconds, getMinutes,
getMonth, getSeconds, getTime, getTimezoneOffset, getYear,
getUTCDate, getUTCDay, getUTCFullYear, getUTCHours,
getUTCMilliseconds, getUTCMinutes, getUTCMonth,
getUTCSeconds,
setDate, setFullYear, setHours, setMilliseconds, setMinutes, setMonth,
setSeconds, setTime, setYear,
setUTCDate, setUTCFullYear, setUTCHours, setUTCMilliseconds,
setUTCMinutes, setUTCMonth, setUTCSeconds,
toGMTString, toLocaleString, toUTCString, parse, UTC
Declarations Function
new
this
var
with
Function Creation Function
arguments, length
Global Methods Global
escape, unescape
eval
isFinite, isNaN
parseInt, parseFloat
Math Math
abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min, pow,
random, round, sin, sqrt, tan,
E, LN2, LN10, LOG2E, LOG10E, PI, SQRT1_2, SQRT2
Numbers
Number
MAX_VALUE, MIN_VALUE
NaN
NEGATIVE_INFINITY, POSITIVE_INFINITY
Object Creation Object
new
constructor, prototype, instanceof, toString, valueOf
Operators Addition (+), Subtraction (-)
Modulus arithmetic (%)
Multiplication (*), Division (/)
Negation (-)
Equality (==), Inequality (!=)
Less Than (<), Less Than or Equal To (<=)
Greater Than (>)
Greater Than or Equal To (>=)
Logical And(&&), Or (||), Not (!)
Bitwise And (&), Or (|), Not (~), Xor (^)
Bitwise Left Shift (<<), Shift Right (>>)
Unsigned Shift Right (>>>)
Conditional (?:)
Comma (, )
delete, typeof, void
Decrement ( ), Increment (++)
Objects Array
Boolean
Date
Function
Global
Math
Number
Object
String
Strings String
charAt, charCodeAt, fromCharCode
indexOf, lastIndexOf
split
toLowerCase, toUpperCase
length
JScript
Category Feature/Keyword
Array Handling concat, slice
VBArray
dimensions, getItem, lbound, toArray, ubound
Conditional Compilation @cc_on
@if Statement
@set Statement
Conditional Compilation Variables
Control flow do...while
Labeled
switch
Dates and Time getVarDate
Enumeration Enumerator
atEnd, item, moveFirst, moveNext
Error Handling Error
description, number
throw, try...catch
Function Creation caller
Operators Identity (===), Nonidentity (!==)
Objects Enumerator
RegExp
Regular Expression
VBArray
ActiveXObject
GetObject
Regular Expressions and Pattern RegExp
Matching index, input, lastIndex, $1...$9, source, compile, exec, test
Regular Expression Syntax
Script Engine Identification ScriptEngine
ScriptEngineBuildVersion
ScriptEngineMajorVersion
ScriptEngineMinorVersion
Strings concat, slice
match, replace, search
anchor, big, blink, bold, fixed, fontcolor, fontsize, italics, link, small,
strike, sub, sup
JScript
Math.abs(number)
The required number argument is a numeric expression for which the absolute value is needed.
Remarks
Example
function ComparePosNegVal(n)
{
var s;
var v1 = Math.abs(n);
var v2 = Math.abs(-n);
if (v1 == v2)
s = "The absolute values of " + n + " and "
s += -n + " are identical.";
return(s);
}
Requirements
Version 1
See Also
JScript
abs Method 1
2 abs Method
2 abs Method
acos Method
Returns the arccosine of a number.
Math.acos(number)
The required number argument is a numeric expression for which the arccosine is needed.
Remarks
Requirements
Version 1
See Also
asin Method | atan Method | cos Method | sin Method | tan Method
JScript
acos Method 1
2 acos Method
2 acos Method
anchor Method
Places an HTML anchor with a NAME attribute around specified text in the object.
strVariable.anchor(anchorString)
Arguments
strVariable
Required. Any String object or literal.
anchorString
Required. Text you want to place in the NAME attribute of an HTML anchor.
Remarks
Call the anchor method to create a named anchor out of a String object. The following example demonstrates
how the anchor method accomplishes this:
No checking is done to see if the tag has already been applied to the string.
Requirements
Version 1
See Also
JScript
anchor Method 1
2 anchor Method
2 anchor Method
asin Method
Returns the arcsine of a number.
Math.asin(number)
The required number argument is a numeric expression for which the arcsine is needed.
Remarks
Requirements
Version 1
See Also
acos Method | atan Method | cos Method | Math Object Methods | sin Method | tan Method
JScript
asin Method 1
2 asin Method
2 asin Method
atan Method
Returns the arctangent of a number.
Math.atan(number)
The required number argument is a numeric expression for which the arctangent is needed.
Remarks
Requirements
Version 1
See Also
acos Method | asin Method | atan2 Method | cos Method | Math Object Methods | sin Method | tan Method
JScript
atan Method 1
2 atan Method
2 atan Method
atan2 Method
Returns the angle (in radians) from the X axis to a point (y,x).
Math.atan2(y, x)
Arguments
x
Required. A numeric expression representing the cartesian x-coordinate.
y
Required. A numeric expression representing the cartesian y-coordinate.
Remarks
The return value is between -pi and pi, representing the angle of the supplied (y,x) point.
Requirements
Version 1
See Also
JScript
atan2 Method 1
2 atan2 Method
2 atan2 Method
big Method
Places HTML <BIG> tags around text in a String object.
strVariable.big( )
Remarks
The example that follows shows how the big method works:
No checking is done to see if the tag has already been applied to the string.
Requirements
Version 1
See Also
JScript
big Method 1
2 big Method
2 big Method
blink Method
Places HTML <BLINK> tags around text in a String object.
strVariable.blink( )
Remarks
No checking is done to see if the tag has already been applied to the string.
Requirements
Version 1
See Also
JScript
blink Method 1
2 blink Method
2 blink Method
bold Method
Places HTML <B> tags around text in a String object.
strVariable.bold()
Remarks
No checking is done to see if the tag has already been applied to the string.
Requirements
Version 1
See Also
JScript
bold Method 1
2 bold Method
2 bold Method
ceil Method
Returns the smallest integer greater than or equal to its numeric argument.
Math.ceil(number)
Remarks
The return value is an integer value equal to the smallest integer greater than or equal to its numeric argument.
Requirements
Version 1
See Also
JScript
ceil Method 1
2 ceil Method
2 ceil Method
charAt Method
Returns the character at the specified index.
strObj.charAt(index)
Arguments
strObj
Required. Any String object or literal.
index
Required. Zero-based index of the desired character. Valid values are between 0 and the length of the
string minus 1.
Remarks
The charAt method returns a character value equal to the character at the specified index. The first character
in a string is at index 0, the second is at index 1, and so forth. Values of index out of valid range return an
empty string.
Example
function charAtTest(n){
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Initialize variable.
var s; // Declare variable.
s = str.charAt(n - 1); // Get correct character
// from position n 1.
return(s); // Return character.
}
Requirements
Version 1
See Also
JScript
charAt Method 1
2 charAt Method
2 charAt Method
compile Method
Compiles a regular expression into an internal format for faster execution.
rgExp.compile(pattern, [flags])
Arguments
rgExp
Required. An instance of a Regular Expression object. Can be a variable name or a literal.
pattern
Required. A string expression containing a regular expression pattern to be compiled
flags
Optional. Available flags, which may be combined, are:
• g (global search for all occurrences of pattern)
• i (ignore case)
• m (multiline search)
Remarks
The compile method converts pattern into an internal format for faster execution. This allows for more
efficient use of regular expressions in loops, for example. A compiled regular expression speeds things up
when reusing the same expression repeatedly. No advantage is gained, however, if the regular expression
changes.
Example
function CompileDemo(){
var rs;
var s = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPp"
// Create regular expression for uppercase only.
var r = new RegExp("[A-Z]", "g");
var a1 = s.match(r) // Find matches.
// Compile the regular expression for lowercase only.
r.compile("[a-z]", "g");
var a2 = s.match(r) // Find matches.
return(a1 + "\n" + a2;
}
Requirements
Version 3
See Also
Regular Expression Object Methods | Regular Expression Object Properties | Regular Expression Syntax
compile Method 1
2 compile Method
JScript
2 compile Method
concat Method (Array)
Returns a new array consisting of a combination of two or more arrays.
Arguments
array1
Required. The Array object to which all other arrays are concatenated.
item1,. . ., itemN
Optional. Additional items to add to the end of array1.
Remarks
The concat method returns an Array object containing the concatenation of array1 and any other supplied
items.
The items to be added (item1
itemN) to the array are added, in order, from left to right. If one of the items is
an array, its contents are added to the end of array1. If the item is anything other than an array, it is added to
the end of the array as a single array element.
• For an object reference copied from any of the arrays being concatenated to the new array, the object
reference continues to point to the same object. A change in either the new array or the original array
will result in a change to the other.
• For a numeric or string value being concatenated to the new array, only the value is copied. Changes
in a value in one array does not affect the value in the other.
Example
The following example illustrates the use of the concat method when used with an array:
function ConcatArrayDemo(){
var a, b, c, d;
a = new Array(1,2,3);
b = "JScript";
c = new Array(42, "VBScript);
d = a.concat(b, c);
//Returns the array [1, 2, 3, "JScript", 42, "VBScript"]
return(d);
}
Requirements
Version 3
See Also
JScript
Arguments
string1
Required. The String object or literal to which all other specified strings are concatenated.
string2,. . ., stringN
Optional. String objects or literals to concatenate to the end of string1.
Remarks
The result of the concat method is equivalent to: result = string1 + string2 + string3 +
+ stringN. A change
of value in either a source or result string does not affect the value in the other string. If any of the arguments
are not strings, they are first converted to strings before being concatenated to string1.
Example
The following example illustrates the use of the concat method when used with a string:
function concatDemo(){
var str1 = "ABCDEFGHIJKLM"
var str2 = "NOPQRSTUVWXYZ";
var s = str1.concat(str2);
// Return concatenated string.
return(s);
}
Requirements
Version 3
See Also
Addition Operator (+) | Array Object | concat Method (Array) | String Object Methods
JScript
Math.cos(number)
The required number argument is a numeric expression for which the cosine is needed.
Remarks
Requirements
Version 1
See Also
acos Method | asin Method | atan Method | Math Object Methods | sin Method | tan Method
JScript
cos Method 1
2 cos Method
2 cos Method
dimensions Method
Returns the number of dimensions in a VBArray.
array.dimensions( )
Remarks
The dimensions method provides a way to retrieve the number of dimensions in a specified VBArray.
The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe
array. The second part is JScript code that determines the number of dimensions in the safe array and the
upper bound of each dimension. Both of these parts go into the <HEAD> section of an HTML page. The third
part is the JScript code that goes in the <BODY> section to run the other two parts.
<HEAD>
<SCRIPT LANGUAGE="VBScript">
<!--
Function CreateVBArray()
Dim i, j, k
Dim a(2, 2)
k = 1
For i = 0 To 2
For j = 0 To 2
a(j, i) = k
k = k + 1
Next
Next
CreateVBArray = a
End Function
-->
</SCRIPT>
<SCRIPT LANGUAGE="JScript">
<!--
function VBArrayTest(vba)
{
var i, s;
var a = new VBArray(vba);
for (i = 1; i <= a.dimensions(); i++)
{
s = "The upper bound of dimension ";
s += i + " is ";
s += a.ubound(i)+ ".<BR>";
}
return(s);
}
-->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT language="jscript">
document.write(VBArrayTest(CreateVBArray()));
</SCRIPT>
</BODY>
dimensions Method 1
2 dimensions Method
Requirements
Version 3
See Also
JScript
2 dimensions Method
escape Method
Encodes String objects so they can be read on all computers.
escape(charString)
Remarks
The escape method returns a string value (in Unicode format) that contains the contents of charstring. All
spaces, punctuation, accented characters, and any other non-ASCII characters are replaced with %xx
encoding, where xx is equivalent to the hexadecimal number representing the character. For example, a space
is returned as "%20."
Characters with a value greater than 255 are stored using the %uxxxx format.
Note The escape method should not be used to encode Uniform Resource Identifiers (URI).
Use encodeURI and encodeURIComponent methods instead.
Requirements
Version 1
See Also
JScript
escape Method 1
2 escape Method
2 escape Method
eval Method
Evaluates JScript code and executes it.
eval(codeString)
The required codeString argument is a string value that contains valid JScript code. This string is parsed by
the JScript parser and executed.
Remarks
The eval function allows dynamic execution of JScript source code. For example, the following code creates a
new variable mydate that contains a Date object:
The code passed to the eval method is executed in the same context as the call to the eval method.
Requirements
Version 1
See Also
String Object
JScript
eval Method 1
2 eval Method
2 eval Method
exec Method
Executes a search on a string using a regular expression pattern, and returns an array containing the results of
that search.
rgExp.exec(str)
Arguments
rgExp
Required. An instance of a Regular Expression object containing the regular expression pattern and
applicable flags.
str
Required. The String object or string literal on which to perform the search.
Remarks
If the exec method does not find a match, it returns null. If it finds a match, exec returns an array, and the
properties of the global RegExp object are updated to reflect the results of the match. Element zero of the
array contains the entire match, while elements 1 n contain any submatches that have occurred within the
match. This behavior is identical to the behavior of the match method without the global flag (g) set.
If the global flag is set for a regular expression, exec searches the string beginning at the position indicated by
the value of lastIndex. If the global flag is not set, exec ignores the value of lastIndex and searches from the
beginning of the string.
The array returned by the exec method has three properties, input, index and lastIndex. The input property
contains the entire searched string. The index property contains the position of the matched substring within
the complete searched string. The lastIndex property contains the position following the last character in the
match.
Example
function RegExpTest(){
var ver = Number(ScriptEngineMajorVersion() + "." + ScriptEngineMinorVersion())
if (ver >= 5.5){ //Test JScript version.
var src = "The rain in Spain falls mainly in the plain.";
var re = /\w+/g; //Create regular expression pattern.
var arr;
while ((arr = re.exec(src)) != null)
document.write(arr.index + "-" + arr.lastIndex + "\t" + arr);
}
else{
alert("You need a newer version of JScript for this to work");
}
}
Requirements
Version 3
exec Method 1
2 exec Method
See Also
match Method | RegExp Object | Regular Expression Object Methods | Regular Expression Object Properties |
Regular Expression Syntax | search method | test Method
JScript
2 exec Method
exp Method
Returns e (the base of natural logarithms) raised to a power.
Math.exp(number)
Remarks
The return value is enumber. The constant e is Euler's constant, approximately equal to 2.178 and number is the
supplied argument.
Requirements
Version 1
See Also
JScript
exp Method 1
2 exp Method
2 exp Method
fixed Method
Places HTML <TT> tags around text in a String object.
strVariable.fixed( )
Remarks
No checking is done to see if the tag has already been applied to the string.
Requirements
Version 1
See Also
JScript
fixed Method 1
2 fixed Method
2 fixed Method
floor Method
Returns the greatest integer less than or equal to its numeric argument.
Math.floor(number)
Remarks
The return value is an integer value equal to the greatest integer less than or equal to its numeric argument.
Requirements
Version 1
See Also
JScript
floor Method 1
2 floor Method
2 floor Method
fontcolor Method
Places an HTML <FONT> tag with the COLOR attribute around the text in a String object.
strVariable.fontcolor(colorVal)
Arguments
strVariable
Required. Any String object or literal.
colorVal
Required. String value containing a color value. This can either be the hexadecimal value for a color,
or the predefined name for a color.
Remarks
Valid predefined color names depend on your JScript host (browser, server, and so forth). They may also vary
from version to version of your host. Check your host documentation for more information.
No checking is done to see if the tag has already been applied to the string.
Requirements
Version 1
See Also
JScript
fontcolor Method 1
2 fontcolor Method
2 fontcolor Method
fontsize Method
Places an HTML <FONT> tag with the SIZE attribute around the text in a String object.
strVariable.fontsize(intSize)
Arguments
strVariable
Required. Any String object or literal.
intSize
Required. Integer value that specifies the size of the text.
Remarks
Valid integer values depend on your Microsoft JScript host. See your host documentation for more
information.
No checking is done to see if the tag has already been applied to the string.
Requirements
Version 1
See Also
JScript
fontsize Method 1
2 fontsize Method
2 fontsize Method
getDate Method
Returns the day of the month value in a Date object using local time.
dateObj.getDate()
Remarks
To get the date value using Universal Coordinated Time (UTC), use the getUTCDate method.
The return value is an integer between 1 and 31 that represents the date value in the Date object.
Example
function DateDemo(){
var d, s = "Today's date is: ";
d = new Date();
s += (d.getMonth() + 1) + "/";
s += d.getDate() + "/";
s += d.getYear();
return(s);
}
Requirements
Version 1
See Also
JScript
getDate Method 1
2 getDate Method
2 getDate Method
getDay Method
Returns the day of the week value in a Date object using local time.
dateObj.getDay()
Remarks
To get the day using Universal Coordinated Time (UTC), use the getUTCDay method.
The value returned from the getDay method is an integer between 0 and 6 representing the day of the week
and corresponds to a day of the week as follows:
function DateDemo(){
var d, day, x, s = "Today is: ";
var x = new Array("Sunday", "Monday", "Tuesday");
var x = x.concat("Wednesday","Thursday", "Friday");
var x = x.concat("Saturday");
d = new Date();
day = d.getDay();
return(s += x[day]);
}
Requirements
Version 1
See Also
JScript
getDay Method 1
2 getDay Method
2 getDay Method
getHours Method
Returns the hours value in a Date object using local time.
dateObj.getHours()
Remarks
To get the hours value using Universal Coordinated Time (UTC), use the getUTCHours method.
The getHours method returns an integer between 0 and 23, indicating the number of hours since midnight. A
zero occurs in two situations: the time is before 1:00:00 am, or the time was not stored in the Date object
when the object was created. The only way to determine which situation you have is to also check the minutes
and seconds for zero values. If they are all zeroes, it is nearly certain that the time was not stored in the Date
object.
function TimeDemo(){
var d, s = "The current local time is: ";
var c = ":";
d = new Date();
s += d.getHours() + c;
s += d.getMinutes() + c;
s += d.getSeconds() + c;
s += d.getMilliseconds();
return(s);
}
Requirements
Version 1
See Also
JScript
getHours Method 1
2 getHours Method
2 getHours Method
getMinutes Method
Returns the minutes value in a Date object using local time.
dateObj.getMinutes()
Remarks
To get the minutes value using Universal Coordinated Time (UTC), use the getUTCMinutes method.
The getMinutes method returns an integer between 0 and 59 equal to the minutes value stored in the Date
object. A zero is returned in two situations: when the time is less than one minute after the hour, or when the
time was not stored in the Date object when the object was created. The only way to determine which
situation you have is to also check the hours and seconds for zero values. If they are all zeroes, it is nearly
certain that the time was not stored in the Date object.
Example
function TimeDemo(){
var d, s = "The current local time is: ";
var c = ":";
d = new Date();
s += d.getHours() + c;
s += d.getMinutes() + c;
s += d.getSeconds() + c;
s += d.getMilliseconds();
return(s);
}
Requirements
Version 3
See Also
JScript
getMinutes Method 1
2 getMinutes Method
2 getMinutes Method
getMonth Method
Returns the month value in the Date object using local time.
dateObj.getMonth()
Remarks
To get the month value using Universal Coordinated Time (UTC), use the getUTCMonth method.
The getMonth method returns an integer between 0 and 11 indicating the month value in the Date object. The
integer returned is not the traditional number used to indicate the month. It is one less. If "Jan 5, 1996
08:47:00" is stored in a Date object, getMonth returns 0.
Example
function DateDemo(){
var d, s = "Today's date is: ";
d = new Date();
s += (d.getMonth() + 1) + "/";
s += d.getDate() + "/";
s += d.getYear();
return(s);
}
Requirements
Version 1
See Also
JScript
getMonth Method 1
2 getMonth Method
2 getMonth Method
getSeconds Method
Returns the seconds value in a Date object using local time.
dateObj.getSeconds()
Remarks
To get the seconds value using Universal Coordinated Time (UTC), use the getUTCSeconds method.
The getSeconds method returns an integer between 0 and 59 indicating the seconds value of the indicated
Date object. A zero is returned in two situations. One occurs when the time is less than one second into the
current minute. The other occurs when the time was not stored in the Date object when the object was created.
The only way to determine which situation you have is to also check the hours and minutes for zero values. If
they are all zeroes, it is nearly certain that the time was not stored in the Date object.
Example
function TimeDemo(){
var d, s = "The current local time is: ";
var c = ":";
d = new Date();
s += d.getHours() + c;
s += d.getMinutes() + c;
s += d.getSeconds() + c;
s += d.getMilliseconds();
return(s);
}
Requirements
Version 1
See Also
JScript
getSeconds Method 1
2 getSeconds Method
2 getSeconds Method
getTime Method
Returns the time value in a Date object.
dateObj.getTime()
Remarks
The getTime method returns an integer value representing the number of milliseconds between midnight,
January 1, 1970 and the time value in the Date object. The range of dates is approximately 285,616 years
from either side of midnight, January 1, 1970. Negative numbers indicate dates prior to 1970.
When doing multiple date and time calculations, it is frequently useful to define variables equal to the number
of milliseconds in a day, hour, or minute. For example:
Example
function GetTimeTest(){
var d, s, t;
var MinMilli = 1000 * 60;
var HrMilli = MinMilli * 60;
var DyMilli = HrMilli * 24;
d = new Date();
t = d.getTime();
s = "It's been "
s += Math.round(t / DyMilli) + " days since 1/1/70";
return(s);
}
Requirements
Version 1
See Also
JScript
getTime Method 1
2 getTime Method
2 getTime Method
getTimezoneOffset Method
Returns the difference in minutes between the time on the host computer and Universal Coordinated Time
(UTC).
dateObj.getTimezoneOffset()
Remarks
The getTimezoneOffset method returns an integer value representing the number of minutes between the
time on the current machine and UTC. These values are appropriate to the computer the script is executed on.
If it is called from a server script, the return value is appropriate to the server. If it is called from a client
script, the return value is appropriate to the client.
This number will be positive if you are behind UTC (e.g., Pacific Daylight Time), and negative if you are
ahead of UTC (e.g., Japan).
For example, suppose a server in New York City is contacted by a client in Los Angeles on December 1.
getTimezoneOffset returns 480 if executed on the client, or 300 if executed on the server.
Example
function TZDemo(){
var d, tz, s = "The current local time is ";
d = new Date();
tz = d.getTimezoneOffset();
if (tz < 0)
s += tz / 60 + " hours before GMT";
else if (tz == 0)
s += "GMT";
else
s += tz / 60 + " hours after GMT";
return(s);
}
Requirements
Version 1
See Also
JScript
getTimezoneOffset Method 1
2 getTimezoneOffset Method
2 getTimezoneOffset Method
getVarDate Method
Returns the VT_DATE value in a Date object.
dateObj.getVarDate()
Remarks
The getVarDate method is used when interacting with COM objects, ActiveX® objects or other objects that
accept and return date values in VT_DATE format, such as Visual Basic and VBScript. The actual format is
dependent on regional settings and should not be replied upon within JScript.
Requirements
Version 3
See Also
JScript
getVarDate Method 1
2 getVarDate Method
2 getVarDate Method
getYear Method
Returns the year value in a Date object.
dateObj.getYear()
Remarks
This method is obsolete, and is provided for backwards compatibility only. Use the getFullYear method
instead.
For the years 1900 though 1999, the year is a 2-digit integer value returned as the difference between the
stored year and 1900. For dates outside that period, the 4-digit year is returned. For example, 1996 is returned
as 96, but 1825 and 2025 are returned as-is.
Note For JScript version 1.0, getYear returns a value that is the result of the subtraction of
1900 from the year value in the provided Date object, regardless of the value of the year. For
example, the year 1899 is returned as -1 and the year 2000 is returned as 100.
Example
function DateDemo(){
var d, s = "Today's date is: ";
d = new Date();
s += (d.getMonth() + 1) + "/";
s += d.getDate() + "/";
s += d.getYear();
return(s);
}
Requirements
Version 1
See Also
JScript
getYear Method 1
2 getYear Method
2 getYear Method
indexOf Method
Returns the character position where the first occurrence of a substring occurs within a String object.
strObj.indexOf(subString[, startIndex])
Arguments
strObj
Required. A String object or literal.
subString
Required. Substring to search for within the String object.
startIndex
Optional. Integer value specifying the index to begin searching within the String object. If omitted,
searching starts at the beginning of the string.
Remarks
The indexOf method returns an integer value indicating the beginning of the substring within the String
object. If the substring is not found, a -1 is returned.
If startindex is negative, startindex is treated as zero. If it is larger than the greatest character position index, it
is treated as the largest possible index.
Searching is performed from left to right. Otherwise, this method is identical to lastIndexOf.
Example
function IndexDemo(str2){
var str1 = "BABEBIBOBUBABEBIBOBU"
var s = str1.indexOf(str2);
return(s);
}
Requirements
Version 1
See Also
JScript
indexOf Method 1
2 indexOf Method
2 indexOf Method
italics Method
Places HTML <I> tags around text in a String object.
strVariable.italics( )
"String Literal".italics( )
Remarks
<I>This is a string</I>
No checking is done to see if the tag has already been applied to the string.
Requirements
Version 1
See Also
JScript
italics Method 1
2 italics Method
2 italics Method
item Method
Returns the current item in the collection.
enumObj.item()
Remarks
The item method returns the current item. If the collection is empty or the current item is undefined, it returns
undefined.
Example
In following code, the item method is used to return a member of the Drives collection.
function ShowDriveList(){
var fso, s, n, e, x;
fso = new ActiveXObject("Scripting.FileSystemObject");
e = new Enumerator(fso.Drives);
s = "";
for (; !e.atEnd(); e.moveNext())
{
x = e.item();
s = s + x.DriveLetter;
s += " - ";
if (x.DriveType == 3)
n = x.ShareName;
else if (x.IsReady)
n = x.VolumeName;
else
n = "[Drive not ready]";
s += n + "<br>";
}
return(s);
}
Requirements
Version 3
See Also
JScript
item Method 1
2 item Method
2 item Method
join Method
Returns a string value consisting of all the elements of an array concatenated together and separated by the
specified separator character.
arrayObj.join(separator)
Arguments
arrayObj
Required. An Array object.
separator
Required. A String object used to separate one element of an array from the next in the resulting
String object. If omitted, the array elements are separated with a comma.
Remarks
Example
function JoinDemo(){
var a, b;
a = new Array(0,1,2,3,4);
b = a.join("-");
return(b);
}
Requirements
Version 2
See Also
JScript
join Method 1
2 join Method
2 join Method
lastIndexOf Method
Returns the last occurrence of a substring within a String object.
strObj.lastIndexOf(substring[, startindex])
Arguments
strObj
Required. A String object or literal.
substring
Required. The substring to search for within the String object.
startindex
Optional. Integer value specifying the index to begin searching within the String object. If omitted,
searching begins at the end of the string.
Remarks
The lastIndexOf method returns an integer value indicating the beginning of the substring within the String
object. If the substring is not found, a -1 is returned.
If startindex is negative, startindex is treated as zero. If it is larger than the greatest character position index, it
is treated as the largest possible index.
function lastIndexDemo(str2)
{
var str1 = "BABEBIBOBUBABEBIBOBU"
var s = str1.lastIndexOf(str2);
return(s);
}
Requirements
Version 1
See Also
JScript
lastIndexOf Method 1
2 lastIndexOf Method
2 lastIndexOf Method
lbound Method
Returns the lowest index value used in the specified dimension of a VBArray.
safeArray.lbound(dimension)
Arguments
safeArray
Required. A VBArray object.
dimension
Optional. The dimension of the VBArray for which the lower bound index is wanted. If omitted,
lbound behaves as if a 1 was passed.
Remarks
If the VBArray is empty, the lbound method returns undefined. If dimension is greater than the number of
dimensions in the VBArray, or is negative, the method generates a "Subscript out of range" error.
Example
The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe
array. The second part is JScript code that determines the number of dimensions in the safe array and the
lower bound of each dimension. Since the safe array is created in VBScript rather than Visual Basic, the lower
bound will always be zero. Both of these parts go into the <HEAD> section of an HTML page. The third part
is the JScript code that goes in the <BODY> section to run the other two parts.
<HEAD>
<SCRIPT LANGUAGE="VBScript">
<!--
Function CreateVBArray()
Dim i, j, k
Dim a(2, 2)
k = 1
For i = 0 To 2
For j = 0 To 2
a(j, i) = k
k = k + 1
Next
Next
CreateVBArray = a
End Function
-->
</SCRIPT>
<SCRIPT LANGUAGE="JScript">
<!--
function VBArrayTest(vba){
var i, s;
var a = new VBArray(vba);
for (i = 1; i <= a.dimensions(); i++)
{
s = "The lower bound of dimension ";
s += i + " is ";
s += a.lbound(i)+ ".<BR>";
return(s);
}
}
-->
</SCRIPT>
lbound Method 1
2 lbound Method
</HEAD>
<BODY>
<SCRIPT language="jscript">
document.write(VBArrayTest(CreateVBArray()));
</SCRIPT>
</BODY>
Requirements
Version 3
See Also
JScript
2 lbound Method
link Method
Places an HTML anchor with an HREF attribute around the text in a String object.
strVariable.link(linkstring)
"String Literal".link(linkstring)
The linkstring argument is the text that you want to place in the HREF attribute of the HTML anchor.
Remarks
Call the link method to create a hyperlink out of a String object. The following is an example of how the
method accomplishes this:
No checking is done to see if the tag has already been applied to the string.
Requirements
Version 1
See Also
JScript
link Method 1
2 link Method
2 link Method
log Method
Returns the natural logarithm of a number.
Math.log(number)
The required number argument is a numeric expression for which the natural logarithm is sought.
Return Value
Requirements
Version 1
See Also
JScript
log Method 1
2 log Method
2 log Method
match Method
Executes a search on a string using a regular expression pattern, and returns an array containing the results of
that search.
stringObj.match(rgExp)
Arguments
stringObj
Required. The String object or string literal on which to perform the search.
rgExp
Required. An instance of a Regular Expression object containing the regular expression pattern and
applicable flags. Can also be a variable name or string literal containing the regular expression pattern
and flags.
Remarks
If the match method does not find a match, it returns null. If it finds a match, match returns an array, and the
properties of the global RegExp object are updated to reflect the results of the match.
The array returned by the match method has three properties, input, index and lastIndex. The input property
contains the entire searched string. The index property contains the position of the matched substring within
the complete searched string. The lastIndex property contains the position following the last character in the
last match.
If the global flag (g) is not set, Element zero of the array contains the entire match, while elements 1 n
contain any submatches that have occurred within the match. This behavior is identical to the behavior of the
exec method without the global flag set. If the global flag is set, elements 0 - n contain all matches that
occurred.
Example
function MatchDemo(){
var r, re; //Declare variables.
var s = "The rain in Spain falls mainly in the plain";
re = /ain/i; //Create regular expression pattern.
r = s.match(re); //Attempt match on search string.
return(r); //Return first occurrence of "ain".
}
This example illustrates the use of the match method with the g flag set.
function MatchDemo(){
var r, re; //Declare variables.
var s = "The rain in Spain falls mainly in the plain";
re = /ain/ig; //Create regular expression pattern.
r = s.match(re); //Attempt match on search string.
return(r); //Return array containing all four
// occurrences of "ain".
}
The following lines of code illustrate the use of a string literal with the match method.
var r, re = "Spain";
match Method 1
2 match Method
r = "The rain in Spain".replace(re, "Canada");
Requirements
Version 3
See Also
exec Method | RegExp Object | replace Method | search Method | String Object Methods | test Method
JScript
2 match Method
max Method
Returns the greater of zero or more supplied numeric expressions.
The optional number1, number2, . . ., numberN arguments are numeric expressions to be evaluated.
Remarks
If no arguments are provided, the return value is equal to NEGATIVE_INFINITY. If any argument is NaN,
the return value is also NaN.
Requirements
Version 1
See Also
JScript
max Method 1
2 max Method
2 max Method
min Method
Returns the lesser of zero or more supplied numeric expressions.
The optional number1, number2, . . ., numberN arguments are numeric expressions to be evaluated.
Remarks
If no arguments are provided, the return value is equal to POSITIVE_INFINITY. If any argument is NaN,
the return value is also NaN.
Requirements
Version 1
See Also
JScript
min Method 1
2 min Method
2 min Method
parse Method
Parses a string containing a date, and returns the number of milliseconds between that date and midnight,
January 1, 1970.
Date.parse(dateVal)
The required dateVal argument is either a string containing a date in a format such as "Jan 5, 1996 08:47:00"
or a VT_DATE value retrieved from an ActiveX® object or other object.
Remarks
The parse method returns an integer value representing the number of milliseconds between midnight,
January 1, 1970 and the date supplied in dateVal.
The parse method is a static method of the Date object. Because it is a static method, it is invoked as shown
in the following example, rather than invoked as a method of a created Date object.
The following rules govern what the parse method can successfully parse:
• Short dates can use either a "/" or "-" date separator, but must follow the month/day/year format, for
example "7/20/96".
• Long dates of the form "July 10 1995" can be given with the year, month, and day in any order, and
the year in 2-digit or 4-digit form. If you use the 2-digit form, the year must be greater than or equal
to 70.
• Any text inside parentheses is treated as a comment. These parentheses may be nested.
• Both commas and spaces are treated as delimiters. Multiple delimiters are permitted.
• Month and day names must have two or more characters. Two character names that are not unique are
resolved as the last match. For example, "Ju" is resolved as July, not June.
• The stated day of the week is ignored if it is incorrect given the remainder of the supplied date. For
example, "Tuesday November 9 1996" is accepted and parsed even though that date actually falls on a
Friday. The resulting Date object contains "Friday November 9 1996".
• JScript handles all standard time zones, as well as Universal Coordinated Time (UTC) and Greenwich
Mean Time (GMT).
• Hours, minutes, and seconds are separated by colons, although all need not be specified. "10:",
"10:11", and "10:11:12" are all valid.
• If the 24-hour clock is used, it is an error to specify "PM" for times later than 12 noon. For example,
"23:15 PM" is an error.
• A string containing an invalid date is an error. For example, a string containing two years or two
months is an error.
Example
The following example illustrates the use of the parse method. Provide the function with a date and the
function will return the difference between the date provided and 1/1/1970:
function GetTimeTest(testdate){
var s, t; //Declare variables.
var MinMilli = 1000 * 60; //Initialize variables.
var HrMilli = MinMilli * 60;
var DyMilli = HrMilli * 24;
t = Date.parse(testdate); //Parse testdate.
s = "There are " //Create return string.
parse Method 1
2 parse Method
s += Math.round(Math.abs(t / DyMilli)) + " days "
s += "between " + testdate + " and 1/1/70";
return(s); //Return results.
}
Requirements
Version 1
See Also
JScript
2 parse Method
parseFloat Method
Returns a floating-point number converted from a string.
parseFloat(numString)
Remarks
The parseFloat method returns a numerical value equal to the number contained in numString. If no prefix of
numString can be successfully parsed into a floating-point number, NaN (not a number) is returned.
Requirements
Version 1
See Also
JScript
parseFloat Method 1
2 parseFloat Method
2 parseFloat Method
parseInt Method
Returns an integer converted from a string.
parseInt(numString, [radix])
Arguments
numString
Required. A string to convert into a number.
radix
Optional. A value between 2 and 36 indicating the base of the number contained in numString. If not
supplied, strings with a prefix of '0x' are considered hexadecimal and strings with a prefix of '0' are
considered octal. All other strings are considered decimal.
Remarks
The parseInt method returns an integer value equal to the number contained in numString. If no prefix of
numString can be successfully parsed into an integer, NaN (not a number) is returned.
Requirements
Version 1
See Also
JScript
parseInt Method 1
2 parseInt Method
2 parseInt Method
pow Method
Returns the value of a base expression taken to a specified power.
Math.pow(base, exponent)
Arguments
base
Required. The base value of the expression.
exponent
Required. The exponent value of the expression.
Example
Math.pow(10,3);
Requirements
Version 1
See Also
JScript
pow Method 1
2 pow Method
2 pow Method
random Method
Returns a pseudorandom number between 0 and 1.
Math.random( )
Remarks
The pseudorandom number generated is from 0 (inclusive) to 1 (exclusive), that is, the returned number can
be zero, but it will always be less than one. The random number generator is seeded automatically when
JScript is first loaded.
Requirements
Version 1
See Also
JScript
random Method 1
2 random Method
2 random Method
replace Method
Returns a copy of a string with text replaced using a regular expression or search string.
stringObj.replace(rgExp, replaceText)
Arguments
stringObj
Required. The String object or string literal on which to perform the replacement. This string is not
modified by the replace method.
rgExp
Required. An instance of a Regular Expression object containing the regular expression pattern and
applicable flags. Can also be a String object or literal. If rgExp is not an instance of a Regular
Expression object, it is converted to a string, and an exact search is made for the results; no attempt is
made to convert the string into a regular expression.
replaceText
Required. A String object or string literal containing the text to replace for every successful match of
rgExp in stringObj. In JScript 5.5 or later, the replaceText argument can also be a function that returns
the replacement text.
Remarks
The result of the replace method is a copy of stringObj after the specified replacements have been made.
Any of the following match variables can be used to identify the most recent match and the string from which
it came. The match variables can be used in text replacement where the replacement string has to be
determined dynamically.
Characters Meaning
$$ $ (JScript 5.5 or later)
$& Specifies that portion of stringObj that the entire pattern matched. (JScript 5.5 or later)
$` Specifies that portion of stringObj that precedes the match described by $&. (JScript
5.5 or later)
$' Specifies that portion of stringObj that follows the match described by $&. (JScript 5.5
or later)
$n The nth captured submatch, where n is a single decimal digit from 1 through 9. (JScript
5.5 or later)
$nn The nnth captured submatch, where nn is a two-digit decimal number from 01 through
99. (JScript 5.5 or later)
If replaceText is a function, for each matched substring the function is called with the following m + 3
arguments where m is the number of left capturing parentheses in the rgExp. The first argument is the
substring that matched. The next m arguments are all of the captures that resulted from the search. Argument
m + 2 is the offset within stringObj where the match occurred, and argument m + 3 is stringObj. The result is
the string value that results from replacing each matched substring with the corresponding return value of the
function call.
The replace method updates the properties of the global RegExp object.
replace Method 1
2 replace Method
Example
The following example illustrates the use of the replace method to replace the first instance of the word "The"
with the word "A."
function ReplaceDemo(){
var r, re; //Declare variables.
var ss = "The man hit the ball with the bat.\n";
ss += "while the fielder caught the ball with the glove.";
re = /The/g; //Create regular expression pattern.
r = ss.replace(re, "A"); //Replace "A" with "The".
return(r); //Return string with replacement made.
}
In addition, the replace method can also replace subexpressions in the pattern. The following example swaps
each pair of words in the string.
function ReplaceDemo(){
var r, re; //Declare variables.
var ss = "The rain in Spain falls mainly in the plain.";
re = /(\S+)(\s+)(\S+)/g; //Create regular expression pattern.
r = ss.replace(re, "$3$2$1"); //Swap each pair of words.
return(r); //Return resulting string.
}
The following example, which works in JScript 5.5 and later, performs a Fahrenheit to Celsius conversion,
illustrates using a function as replaceText. To see how this function works, pass in a string containing a
number followed immediately by an "F" (e.g., "Water boils at 212").
function f2c(s) {
var test = /(\d+(\.\d*)?)F\b/g; //Initialize pattern.
return(s.replace
(test,
function($0,$1,$2) {
return((($1-32) * 5/9) + "C");
}
)
);
}
document.write(f2c("Water freezes at 32F and boils at 212F."));
Requirements
Version 1
See Also
exec Method | match Method | RegExp Object | search Method | String Object Methods | test Method
JScript
2 replace Method
reverse Method
Returns an Array object with the elements reversed.
arrayObj.reverse( )
Remarks
The reverse method reverses the elements of an Array object in place. It does not create a new Array object
during execution.
If the array is not contiguous, the reverse method creates elements in the array that fill the gaps in the array.
Each of these created elements has the value undefined.
Example
function ReverseDemo(){
var a, l; //Declare variables.
a = new Array(0,1,2,3,4); //Create an array and populate it.
l = a.reverse(); //Reverse the contents of the array.
return(l); //Return the resulting array.
}
Requirements
Version 2
See Also
JScript
reverse Method 1
2 reverse Method
2 reverse Method
round Method
Returns a supplied numeric expression rounded to the nearest integer.
Math.round(number)
The required number argument is the value to be rounded to the nearest integer.
Remarks
If the decimal portion of number is 0.5 or greater, the return value is equal to the smallest integer greater than
number. Otherwise, round returns the largest integer less than or equal to number.
Requirements
Version 1
See Also
JScript
round Method 1
2 round Method
2 round Method
search Method
Returns the position of the first substring match in a regular expression search.
stringObj.search(rgExp)
Arguments
stringObj
Required. The String object or string literal on which to perform the search.
rgExp
Required. An instance of a Regular Expression object containing the regular expression pattern and
applicable flags.
Remarks
The search method indicates if a match is present or not. If a match is found, the search method returns an
integer value that indicates the offset from the beginning of the string where the match occurred. If no match
is found, it returns -1.
Example
function SearchDemo(){
var r, re; //Declare variables.
var s = "The rain in Spain falls mainly in the plain.";
re = /falls/i; //Create regular expression pattern.
r = s.search(re); //Search the string.
return(r); //Return the Boolean result.
}
Requirements
Version 3
See Also
exec Method | match Method | Regular Expression Object | Regular Expression Syntax | replace Method |
String Object Methods | test Method
JScript
search Method 1
2 search Method
2 search Method
setDate Method
Sets the numeric date of the Date object using local time.
dateObj.setDate(numDate)
Arguments
dateObj
Required. Any Date object.
numDate
Required. A numeric value equal to the numeric date.
Remarks
To set the date value using Universal Coordinated Time (UTC), use the setUTCDate method.
If the value of numDate is greater than the number of days in the month stored in the Date object or is a
negative number, the date is set to a date equal to numDate minus the number of days in the stored month. For
example, if the stored date is January 5, 1996, and setDate(32) is called, the date changes to February 1, 1996.
Negative numbers have a similar behavior.
Example
function SetDateDemo(newdate){
var d, s; //Declare variables.
d = new Date(); //Create date object.
d.setDate(newdate); //Set date to newdate.
s = "Current setting is ";
s += d.toLocaleString();
return(s); //Return newly set date.
}
Requirements
Version 3
See Also
JScript
setDate Method 1
2 setDate Method
2 setDate Method
setHours Method
Sets the hour value in the Date object using local time.
Arguments
dateObj
Required. Any Date object.
numHours
Required. A numeric value equal to the hours value.
numMin
Optional. A numeric value equal to the minutes value. Must be supplied if either of the following
arguments is used.
numSec
Optional. A numeric value equal to the seconds value. Must be supplied if the following argument is
used.
numMilli
Optional. A numeric value equal to the milliseconds value.
Remarks
All set methods taking optional arguments use the value returned from corresponding get methods, if you do
not specify an optional argument. For example, if the numMinutes argument is optional, but not specified,
JScript uses the value returned from the getMinutes method.
To set the hours value using Universal Coordinated Time (UTC), use the setUTCHours method.
If the value of an argument is greater than its range or is a negative number, other stored values are modified
accordingly. For example, if the stored date is "Jan 5, 1996 00:00:00", and setHours(30) is called, the date is
changed to "Jan 6, 1996 06:00:00." Negative numbers have a similar behavior.
Example
Requirements
Version 3
See Also
setHours Method 1
2 setHours Method
JScript
2 setHours Method
setMonth Method
Sets the month value in the Date object using local time.
dateObj.setMonth(numMonth[, dateVal])
Arguments
dateObj
Required. Any Date object.
numMonth
Required. A numeric value equal to the month.
dateVal
Optional. A numeric value representing the date. If not supplied, the value from a call to the getDate
method is used.
Remarks
To set the month value using Universal Coordinated Time (UTC), use the setUTCMonth method.
If the value of numMonth is greater than 11 (January is month 0) or is a negative number, the stored year is
modified accordingly. For example, if the stored date is "Jan 5, 1996" and setMonth(14) is called, the date is
changed to "Mar 5, 1997."
Example
function SetMonthDemo(newmonth){
var d, s; //Declare variables.
d = new Date(); //Create Date object.
d.setMonth(newmonth); //Set month.
s = "Current setting is ";
s += d.toLocaleString();
return(s); //Return new setting.
}
Requirements
Version 1
See Also
JScript
setMonth Method 1
2 setMonth Method
2 setMonth Method
setSeconds Method
Sets the seconds value in the Date object using local time.
dateObj.setSeconds(numSeconds[, numMilli])
Arguments
dateObj
Required. Any Date object.
numSeconds
Required. A numeric value equal to the seconds value.
numMilli
Optional. A numeric value equal to the milliseconds value.
Remarks
All set methods taking optional arguments use the value returned from corresponding get methods, if you do
not specify an optional argument. For example, if the numMilli argument is optional, but not specified, JScript
uses the value returned from the getMilliseconds method.
To set the seconds value using Universal Coordinated Time (UTC), use the setUTCSeconds method.
If the value of an argument is greater than its range or is a negative number, other stored values are modified
accordingly. For example, if the stored date is "Jan 5, 1996 00:00:00" and setSeconds(150) is called, the date
is changed to "Jan 5, 1996 00:02:30."
Example
Requirements
Version 1
See Also
setSeconds Method 1
2 setSeconds Method
JScript
2 setSeconds Method
setTime Method
Sets the date and time value in the Date object.
dateObj.setTime(milliseconds)
Arguments
dateObj
Required. Any Date object.
milliseconds
Required. An integer value representing the number of elapsed seconds since midnight, January 1,
1970 GMT.
Remarks
If milliseconds is negative, it indicates a date before 1970. The range of available dates is approximately
285,616 years from either side of 1970.
Setting the date and time with the setTime method is independent of the time zone.
Example
function SetTimeTest(newtime){
var d, s; //Declare variables.
d = new Date(); //Create Date object.
d.setTime(newtime); //Set time.
s = "Current setting is ";
s += d.toUTCString();
return(s); //Return new setting.
}
Requirements
Version 1
See Also
JScript
setTime Method 1
2 setTime Method
2 setTime Method
setYear Method
Sets the year value in the Date object.
dateObj.setYear(numYear)
Arguments
dateObj
Required. Any Date object.
numYear
Required. A numeric value equal to the year minus 1900.
Remarks
This method is obsolete, and is maintained for backwards compatibility only. Use the setFullYear method
instead.
To set the year of a Date object to 1997, call setYear(97). To set the year to 2010, call setYear(2010).
Finally, to set the year to a year in the range 0-99, use the setFullYear method.
Note For JScript version 1.0, setYear uses a value that is the result of the addition of 1900
to the year value provided by numYear, regardless of the value of the year. For example, to
set the year to 1899 numYear is -1 and to set the year 2000 numYear is 100.
Requirements
Version 1
See Also
Date Object Methods | getFullYear Method | getUTCFullYear Method | getYear Method | setFullYear Method
| setUTCFullYear Method
JScript
setYear Method 1
2 setYear Method
2 setYear Method
sin Method
Returns the sine of a number.
Math.sin(number)
The number argument is a numeric expression for which the sine is needed.
Remarks
Requirements
Version 1
See Also
acos Method | asin Method | atan Method | cos Method | Math Object Methods | tan Method
JScript
sin Method 1
2 sin Method
2 sin Method
slice Method (Array)
Returns a section of an array.
arrayObj.slice(start, [end])
Arguments
arrayObj
Required. An Array object.
start
Required. The index to the beginning of the specified portion of arrayObj.
end
Optional. The index to the end of the specified portion of arrayObj.
Remarks
The slice method returns an Array object containing the specified portion of arrayObj.
The slice method copies up to, but not including, the element indicated by end. If start is negative, it is treated
as length + start where length is the length of the array. If end is negative, it is treated as length + end where
length is the length of the array. If end is omitted, extraction continues to the end of arrayObj. If end occurs
before start, no elements are copied to the new array.
Example
In the following example, all but the last element of myArray is copied into newArray:
Requirements
Version 3
See Also
JScript
stringObj.slice(start, [end])
Arguments
stringObj
Required. A String object or literal.
start
Required. The index to the beginning of the specified portion of stringObj.
end
Optional. The index to the end of the specified portion of stringObj.
Remarks
The slice method returns a String object containing the specified portion of stringObj.
The slice method copies up to, but not including, the element indicated by end. If start is negative, it is treated
as length + start where length is the length of the string. If end is negative, it is treated as length + end where
length is the length of the string. If end is omitted, extraction continues to the end of stringObj. If end occurs
before start, no characters are copied to the new string.
Example
In the following example, the two uses of the slice method return the same result. In the second example,
negative one (-1) points to the last character in str1 as the ending point.
str1.slice(0)
str2.slice(0,-1)
Requirements
Version 3
See Also
JScript
strVariable.small( )
"String Literal".small( )
Remarks
<SMALL>This is a string</SMALL>
No checking is done to see if the tag has already been applied to the string.
Requirements
Version 1
See Also
JScript
small Method 1
2 small Method
2 small Method
sort Method
Returns an Array object with the elements sorted.
arrayobj.sort(sortFunction)
Arguments
arrayObj
Required. Any Array object.
sortFunction
Optional. The name of the function used to determine the order of the elements. If omitted, the
elements are sorted in ascending, ASCII character order.
Remarks
The sort method sorts the Array object in place; no new Array object is created during execution.
If you supply a function in the sortFunction argument, it must return one of the following values:
• A negative value if the first argument passed is less than the second argument.
• Zero if the two arguments are equivalent.
• A positive value if the first argument is greater than the second argument.
Example
function SortDemo(){
var a, l; //Declare variables.
a = new Array("X" ,"y" ,"d", "Z", "v","m","r");
l = a.sort(); //Sort the array.
return(l); //Return sorted array.
}
Requirements
Version 2
See Also
JScript
sort Method 1
2 sort Method
2 sort Method
split Method
Returns the array of strings that results when a string is separated into substrings.
stringObj.split([separator[, limit]])
Arguments
stringObj
Required. The String object or literal to be split. This object is not modified by the split method.
separator
Optional. A string or an instance of a Regular Expression object identifying one or more characters
to use in separating the string. If omitted, a single-element array containing the entire string is
returned.
limit
Optional. A value used to limit the number of elements returned in the array.
Remarks
The result of the split method is an array of strings split at each point where separator occurs in stringObj.
The separator is not returned as part of any array element.
Example
function SplitDemo(){
var s, ss;
var s = "The rain in Spain falls mainly in the plain.";
// Split at each space character.
ss = s.split(" ");
return(ss);
}
Requirements
Version 3
See Also
concat Method | RegExp Object | Regular Expression Object | Regular Expression Syntax | String Object
Methods
JScript
split Method 1
2 split Method
2 split Method
sqrt Method
Returns the square root of a number.
Math.sqrt(number)
Remarks
Requirements
Version 1
See Also
JScript
sqrt Method 1
2 sqrt Method
2 sqrt Method
strike Method
Places HTML <STRIKE> tags around text in a String object.
strVariable.strike( )
"String Literal".strike( )
Remarks
No checking is done to see if the tag has already been applied to the string.
Requirements
Version 1
See Also
JScript
strike Method 1
2 strike Method
2 strike Method
sub Method
Places HTML <SUB> tags around text in a String object.
strVariable.sub( )
"String Literal".sub( )
Remarks
No checking is done to see if the tag has already been applied to the string.
Requirements
Version 1
See Also
JScript
sub Method 1
2 sub Method
2 sub Method
substr Method
Returns a substring beginning at a specified location and having a specified length.
stringvar.substr(start [, length ])
Arguments
stringvar
Required. A string literal or String object from which the substring is extracted.
start
Required. The starting position of the desired substring. The index of the first character in the string is
zero.
length
Optional. The number of characters to include in the returned substring.
Remarks
If length is zero or negative, an empty string is returned. If not specified, the substring continues to the end of
stringvar.
Example
function SubstrDemo(){
var s, ss; //Declare variables.
var s = "The rain in Spain falls mainly in the plain.";
ss = s.substr(12, 5); //Get substring.
return(ss); // Returns "Spain".
}
Requirements
Version 3
See Also
JScript
substr Method 1
2 substr Method
2 substr Method
substring Method
Returns the substring at the specified location within a String object.
strVariable.substring(start, end)
"String Literal".substring(start, end)
Arguments
start
The zero-based index integer indicating the beginning of the substring.
end
The zero-based index integer indicating the end of the substring.
Remarks
The substring method returns a string containing the substring from start up to, but not including, end.
The substring method uses the lower value of start and end as the beginning point of the substring. For
example, strvar.substring(0, 3) and strvar.substring(3, 0) return the same substring.
The length of the substring is equal to the absolute value of the difference between start and end. For
example, the length of the substring returned in strvar.substring(0, 3) and strvar.substring(3, 0) is three.
Example
function SubstringDemo(){
var ss; //Declare variables.
var s = "The rain in Spain falls mainly in the plain..";
ss = s.substring(12, 17); //Get substring.
return(ss); //Return substring.
}
Requirements
Version 1
See Also
JScript
substring Method 1
2 substring Method
2 substring Method
sup Method
Places HTML <SUP> tags around text in a String object.
strVariable.sup( )
"String Literal".sup( )
Remarks
No checking is done to see if the tag has already been applied to the string.
Requirements
Version 1
See Also
JScript
sup Method 1
2 sup Method
2 sup Method
tan Method
Returns the tangent of a number.
Math.tan(number)
The required number argument is a numeric expression for which the tangent is sought.
Remarks
Requirements
Version 1
See Also
acos Method | asin Method | atan Method | atan2 Method | cos Method | Math Object Methods | sin Method
JScript
tan Method 1
2 tan Method
2 tan Method
test Method
Returns a Boolean value that indicates whether or not a pattern exists in a searched string.
rgExp.test(str)
Arguments
rgExp
Required. An instance of a Regular Expression object containing the regular expression pattern and
applicable flags.
str
Required. The string on which to perform the search.
Remarks
The test method checks to see if a pattern exists within a string and returns true if so, and false otherwise.
The properties of the global RegExp object are not modified by the test method.
Example
The following example illustrates the use of the test method. To use this example, pass the function a regular
expression pattern and a string. The function will test for the occurrence of the regular expression pattern in
the string and return a string indicating the results of that search:
Requirements
Version 3
See Also
RegExp Object | Regular Expression Object | Regular Expression Object Methods | Regular Expression
Object Properties | Regular Expression Syntax
JScript
test Method 1
2 test Method
2 test Method
toGMTString Method
Returns a date converted to a string using Greenwich Mean Time(GMT).
dateObj.toGMTString()
Remarks
The toGMTString method is obsolete, and is provided for backwards compatibility only. It is recommended
that you use the toUTCString method instead.
The toGMTString method returns a String object that contains the date formatted using GMT convention.
The format of the return value is as follows: "05 Jan 1996 00:00:00 GMT."
Requirements
Version 1
See Also
JScript
toGMTString Method 1
2 toGMTString Method
2 toGMTString Method
toLocaleString Method
Returns a date converted to a string using the current locale.
dateObj.toLocaleString()
Remarks
The toLocaleString method returns a String object that contains the date written in the current locale's long
default format.
• For dates between 1601 and 1999 A.D., the date is formatted according to the user's Control Panel
Regional Settings.
• For dates outside this range, the default format of the toString method is used.
For example, in the United States, toLocaleString returns "01/05/96 00:00:00" for January 5. In Europe, it
returns "05/01/96 00:00:00" for the same date, as European convention puts the day before the month.
Note toLocaleString should only be used to display results to a user; it should never be used
as the basis for computation within a script as the returned result is machine-specific.
Example
function toLocaleStrDemo(){
var d, s; //Declare variables.
d = new Date(); //Create Date object.
s = "Current setting is ";
s += d.toLocaleString(); //Convert to current locale.
return(s); //Return converted date
}
Requirements
Version 1
See Also
Applies To: Array Object | Date Object | Number Object | Object Object
JScript
toLocaleString Method 1
2 toLocaleString Method
2 toLocaleString Method
toLowerCase Method
Returns a string where all alphabetic characters have been converted to lowercase.
strVariable.toLowerCase( )
"String Literal".toLowerCase( )
Remarks
Requirements
Version 1
See Also
JScript
toLowerCase Method 1
2 toLowerCase Method
2 toLowerCase Method
toUpperCase Method
Returns a string where all alphabetic characters have been converted to uppercase.
strVariable.toUpperCase( )
"String Literal".toUpperCase( )
Remarks
Example
Requirements
Version 1
See Also
JScript
toUpperCase Method 1
2 toUpperCase Method
2 toUpperCase Method
ubound Method
Returns the highest index value used in the specified dimension of the VBArray.
safeArray.ubound(dimension)
Arguments
safeArray
Required. A VBArray object.
dimension
Optional. The dimension of the VBArray for which the higher bound index is wanted. If omitted,
ubound behaves as if a 1 was passed.
Remarks
If the VBArray is empty, the ubound method returns undefined. If dim is greater than the number of
dimensions in the VBArray, or is negative, the method generates a "Subscript out of range" error.
Example
The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe
array. The second part is JScript code that determines the number of dimensions in the safe array and the
upper bound of each dimension. Both of these parts go into the <HEAD> section of an HTML page. The third
part is the JScript code that goes in the <BODY> section to run the other two parts.
<HEAD>
<SCRIPT LANGUAGE="VBScript">
<!--
Function CreateVBArray()
Dim i, j, k
Dim a(2, 2)
k = 1
For i = 0 To 2
For j = 0 To 2
a(j, i) = k
k = k + 1
Next
Next
CreateVBArray = a
End Function
-->
</SCRIPT>
<SCRIPT LANGUAGE="JScript">
<!--
function VBArrayTest(vba)
{
var i, s;
var a = new VBArray(vba);
for (i = 1; i <= a.dimensions(); i++)
{
s = "The upper bound of dimension ";
s += i + " is ";
s += a.ubound(i)+ ".<BR>";
return(s);
}
}
-->
</SCRIPT>
ubound Method 1
2 ubound Method
</HEAD>
<BODY>
<SCRIPT language="jscript">
document.write(VBArrayTest(CreateVBArray()));
</SCRIPT>
</BODY>
Requirements
Version 3
See Also
JScript
2 ubound Method
unescape Method
Decodes String objects encoded with the escape method.
unescape(charString)
Remarks
The unescape method returns a string value that contains the contents of charstring. All characters encoded
with the %xx hexadecimal form are replaced by their ASCII character set equivalents.
Characters encoded in %uxxxx format (Unicode characters) are replaced with the Unicode character with
hexadecimal encoding xxxx.
Note The unescape method should not be used to decode Uniform Resource Identifiers
(URI). Use decodeURI and decodeURIComponent methods instead.
Requirements
Version 1
See Also
JScript
unescape Method 1
2 unescape Method
2 unescape Method
Array Object
Provides support for creation of arrays of any data type.
Arguments
arrayObj
Required. The variable name to which the Array object is assigned.
size
Optional. The size of the array. As arrays are zero-based, created elements will have indexes from
zero to size -1.
element0,...,elementN
Optional. The elements to place in the array. This creates an array with n + 1 elements, and a length
of n + 1. Using this syntax, you must supply more than one element.
Remarks
After an array is created, the individual elements of the array can be accessed using [ ] notation, for example:
Since arrays in Microsoft JScript are zero-based, the last statement in the preceding example accesses the fifth
element of the array. That element contains the value 4.
If only one argument is passed to the Array constructor, and the argument is a number, it must be an unsigned
32-bit integer (< approximately four billion). That value then becomes the size of the array. If the value is a
number, but is less than zero or is not an integer, a run-time error occurs.
If a single value is passed to the Array constructor, and it is not a number, the length property is set to 1, and
the value of the only element becomes the single, passed-in argument.
Notice that JScript arrays are sparse arrays, that is, although you can allocate an array with many elements,
only the elements that actually contain data exist. This reduces the amount of memory used by the array.
Properties
Methods
concat Method | join Method | pop Method | push Method | reverse Method | shift Method | slice Method | sort
Method | splice Method | toLocaleString Method | toString Method | unshift Method | valueOf Method
Array Object 1
2 Array Object
Requirements
Version 2
See Also
new Operator
JScript
2 Array Object
arguments Object
An object representing the arguments to the currently executing function, and the functions that called it.
[function.]arguments[n]
Arguments
function
Optional. The name of the currently executing Function object.
n
Required. The zero-based index to argument values passed to the Function object.
Remarks
You cannot explicitly create an arguments object. The arguments object only becomes available when a
function begins execution. The arguments object of the function is not an array, but the individual arguments
are accessed the same way array elements are accessed. The index n is actually a reference to one of the 0
n
properties of the arguments object.
Example
Requirements
Version 1
See Also
arguments Object 1
2 arguments Object
JScript
2 arguments Object
Date Object
Enables basic storage and retrieval of dates and times.
Arguments
dateObj
Required. The variable name to which the Date object is assigned.
dateVal
Required. If a numeric value, dateVal represents the number of milliseconds in Universal Coordinated
Time between the specified date and midnight January 1, 1970. If a string, dateVal is parsed
according to the rules in the parse method. The dateVal argument can also be a VT_DATE value as
returned from some ActiveX® objects.
year
Required. The full year, for example, 1976 (and not 76).
month
Required. The month as an integer between 0 and 11 (January to December).
date
Required. The date as an integer between 1 and 31.
hours
Optional. Must be supplied if minutes is supplied. An integer from 0 to 23 (midnight to 11pm) that
specifies the hour.
minutes
Optional. Must be supplied if seconds is supplied. An integer from 0 to 59 that specifies the minutes.
seconds
Optional. Must be supplied if milliseconds is supplied. An integer from 0 to 59 that specifies the
seconds.
ms
Optional. An integer from 0 to 999 that specifies the milliseconds.
Remarks
A Date object contains a number representing a particular instant in time to within a millisecond. If the value
of an argument is greater than its range or is a negative number, other stored values are modified accordingly.
For example, if you specify 150 seconds, JScript redefines that number as two minutes and 30 seconds.
If the number is NaN, the object does not represent a specific instant of time. If you pass no parameters to the
Date object, it is initialized to the current time (UTC). A value must be given to the object before you can use
it.
The range of dates that can be represented in a Date object is approximately 285,616 years on either side of
January 1, 1970.
The Date object has two static methods that are called without creating a Date object. They are parse and
UTC.
Error
function DateDemo(){
Date Object 1
2 Date Object
var d, s = "Today's date is: "; //Declare variables.
d = new Date(); //Create Date object.
s += (d.getMonth() + 1) + "/"; //Get month
s += d.getDate() + "/"; //Get day
s += d.getYear(); //Get year.
return(s); //Return date.
}
Properties
Methods
getDate Method | getDay Method | getFullYear Method | getHours Method | getMilliseconds Method |
getMinutes Method | getMonth Method | getSeconds Method | getTime Method | getTimezoneOffset Method |
getUTCDate Method | getUTCDay Method | getUTCFullYear Method | getUTCHours Method |
getUTCMilliseconds Method | getUTCMinutes Method | getUTCMonth Method | getUTCSeconds Method |
getVarDate Method | getYear Method | setDate Method | setFullYear Method | setHours Method |
setMilliseconds Method | setMinutes Method | setMonth Method | setSeconds Method | setTime Method |
setUTCDate Method | setUTCFullYear Method | setUTCHours Method | setUTCMilliseconds Method |
setUTCMinutes Method | setUTCMonth Method | setUTCSeconds Method | setYear Method | toGMTString
Method | toLocaleString Method | toUTCString Method | toString Method | valueOf Method | parse Method |
UTC Method
Requirements
Version 1
See Also
JScript
2 Date Object
Global Object
An intrinsic object whose purpose is to collect global methods into one object.
The Global object has no syntax. You call its methods directly.
Remarks
The Global object is never used directly, and cannot be created using the new operator. It is created when the
scripting engine is initialized, thus making its methods and properties available immediately.
Properties
Methods
escape Method | eval Method | isFinite Method | isNaN Method | parseFloat Method | parseInt Method |
unescape Method
Requirements
Version 5
See Also
Object Object
JScript
Global Object 1
2 Global Object
2 Global Object
Math Object
An intrinsic object that provides basic mathematics functionality and constants.
Math.[{property | method}]
Arguments
property
Required. Name of one of the properties of the Math. object.
method
Required. Name of one of the methods of the Math. object.
Remarks
The Math object cannot be created using the new operator, and gives an error if you attempt to do so. The
scripting engine creates it when the engine is loaded. All of its methods and properties are available to your
script at all times.
Properties
E Property | LN2 Property | LN10 Property | LOG2E Property | LOG10E Property | PI Property | SQRT1_2
Property | SQRT2 Property
Methods
abs Method | acos Method | asin Method | atan Method | atan2 Method | ceil Method | cos Method | exp
Method | floor Method | log Method | max Method | min Method | pow Method | random Method | round
Method | sin Method | sqrt Method | tan Method
Requirements
Version 1
See Also
Number Object
JScript
Math Object 1
2 Math Object
2 Math Object
Regular Expression Object
An object that contains a regular expression pattern along with flags that identify how to apply the pattern.
Syntax 1
re = /pattern/[flags]
Syntax 2
re = new RegExp("pattern",["flags"])
Arguments
re
Required. The variable name to which the regular expression pattern is assigned.
pattern
Required. The regular expression pattern to use. If you use Syntax 1, delimit the pattern by "/"
characters. If you use Syntax 2, enclose the pattern in quotation marks.
flags
Optional. Enclose flag in quotation marks if you use Syntax 2. Available flags, which may be
combined, are:
• g (global search for all occurrences of pattern)
• i (ignore case)
• m (multiline search)
Remarks
The Regular Expression object should not be confused with the global RegExp object. Even though they
sound the same, they are separate and distinct. The properties of the Regular Expression object contain only
information about one particular Regular Expression instance, while the properties of the global RegExp
object contain continually updated information about each match as it occurs.
Regular Expression objects store patterns used when searching strings for character combinations. After the
Regular Expression object is created, it is either passed to a string method, or a string is passed to one of the
regular expression methods. Information about the most recent search performed is stored in the global
RegExp object.
Use Syntax 1 when you know the search string ahead of time. Use Syntax 2 when the search string is
changing frequently, or is unknown, such as strings taken from user input.
The pattern argument is compiled into an internal format before use. For Syntax 1, pattern is compiled as the
script is loaded. For Syntax 2, pattern is compiled just before use, or when the compile method is called.
Example
The following example illustrates the use of the Regular Expression object by creating an object (re)
containing a regular expression pattern with its associated flags. In this case, the resulting Regular
Expression object is then used by the match method:
function MatchDemo(){
var r, re; //Declare variables.
var s = "The rain in Spain falls mainly in the plain";
re = new RegExp("Spain","i"); //Create regular expression object.
r = s.match(re); //Find a match within string s.
Properties
Methods
Requirements
Version 3
See Also
JScript
Syntax
Arguments
newString
Required. The variable name to which the String object is assigned.
stringLiteral
Optional. Any group of Unicode characters.
Remarks
String objects can be created implicitly using string literals. String objects created in this fashion (referred to
as standard strings) are treated differently than String objects created using the new operator. All string
literals share a common, global string object. If a property is added to a string literal, it is available to all
standard string objects:
alpha.test = 10;
In the previous example, test is now defined for beta and all future string literals. In the following example,
however, added properties are treated differently:
gamma.test = 10;
In this case, test is not defined for delta. Each String object declared as a new String object has its own set of
members. This is the only case where String objects and string literals are handled differently.
Properties
Methods
anchor Method | big Method | blink Method | bold Method | charAt Method | charCodeAt Method | concat
Method | fixed Method | fontcolor Method | fontsize Method | fromCharCode Method | indexOf Method |
italics Method | lastIndexOf Method | link Method | match Method | replace Method | search Method | slice
Method | small Method | split Method | strike Method | sub Method | substr Method | substring Method | sup
Method | toLowerCase Method | toUpperCase Method | toString Method | valueOf Method
String Object 1
2 String Object
Requirements
Version 1
See Also
new Operator
JScript
2 String Object
Addition Assignment Operator (+=)
Adds the value of an expression to the value of a variable and assigns the result to the variable.
result += expression
Arguments
result
Any variable.
expression
Any expression.
Remarks
The underlying subtype of the expressions determines the behavior of the += operator.
If Then
Both expressions are numeric or Boolean Add
Both expressions are strings Concatenate
One expression is numeric and the other is a string Concatenate
Requirements
Version 1
See Also
JScript
Arguments
result
Any variable.
expression
Any expression.
Remarks
The &= operator looks at the binary representation of the values of result and expression and does a bitwise
AND operation on them. The output of this operation behaves like this:
0101 (result)
1100 (expression)
----
0100 (output)
Any time both of the expressions have a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a
0 in that digit.
Requirements
Version 1
See Also
JScript
Arguments
result
Any variable.
expression1
Any expression.
expression2
Any expression.
Remarks
The & operator looks at the binary representation of the values of two expressions and does a bitwise AND
operation on them. The result of this operation behaves as follows:
0101 (expression1)
1100 (expression2)
----
0100 (result)
Any time both of the expressions have a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a
0 in that digit.
Requirements
Version 1
See Also
JScript
Arguments
result
Any variable.
expression1
Any expression.
expression2
Any expression.
Remarks
The << operator shifts the bits of expression1 left by the number of bits specified in expression2. For
example:
var temp
temp = 14 << 2
The variable temp has a value of 56 because 14 (00001110 in binary) shifted left two bits equals 56
(00111000 in binary).
Requirements
Version 1
See Also
<<= Operator | >> Operator | >>> Operator | Operator Precedence | Operator Summary
JScript
result = ~ expression
Arguments
result
Any variable.
expression
Any expression.
Remarks
The ~ operator looks at the binary representation of the values of the expression and does a bitwise negation
operation on it. The result of this operation behaves as follows:
0101 (expression)
----
1010 (result)
Any digit that is a 1 in the expression becomes a 0 in the result. Any digit that is a 0 in the expression
becomes a 1 in the result.
Requirements
Version 1
See Also
JScript
result |= expression
Arguments
result
Any variable.
expression
Any expression.
Remarks
The |= operator looks at the binary representation of the values of result and expression and does a bitwise OR
operation on them. The result of this operation behaves like this:
0101 (result)
1100 (expression)
----
1101 (output)
Any time either of the expressions has a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a
0 in that digit.
Requirements
Version 1
See Also
JScript
Arguments
result
Any variable.
expression1
Any expression.
expression2
Any expression.
Remarks
The | operator looks at the binary representation of the values of two expressions and does a bitwise OR
operation on them. The result of this operation behaves as follows:
0101 (expression1)
1100 (expression2)
----
1101 (result)
Any time either of the expressions has a 1 in a digit, the result will have a 1 in that digit. Otherwise, the result
will have a 0 in that digit.
Requirements
Version 1
See Also
JScript
Arguments
result
Any variable.
expression1
Any expression.
expression2
Any expression.
Remarks
The >> operator shifts the bits of expression1 right by the number of bits specified in expression2. The sign
bit of expression1 is used to fill the digits from the left. Digits shifted off the right are discarded. For example,
after the following code is evaluated, temp has a value of -4: 14 (11110010 in binary) shifted right two bits
equals -4 (11111100 in binary).
var temp
temp = -14 >> 2
Requirements
Version 1
See Also
<< Operator | >>= Operator | >>> Operator | Operator Precedence | Operator Summary
JScript
result ^= expression
Arguments
result
Any variable.
expression
Any expression.
Remarks
The ^= operator looks at the binary representation of the values of two expressions and does a bitwise
exclusive OR operation on them. The result of this operation behaves as follows:
0101 (result)
1100 (expression)
----
1001 (result)
When one, and only one, of the expressions has a 1 in a digit, the result has a 1 in that digit. Otherwise, the
result has a 0 in that digit.
Requirements
Version 1
See Also
JScript
Arguments
result
Any variable.
expression1
Any expression.
expression2
Any expression.
Remarks
The ^ operator looks at the binary representation of the values of two expressions and does a bitwise
exclusive OR operation on them. The result of this operation behaves as follows:
0101 (expression1)
1100 (expression2)
----
1001 (result)
When one, and only one, of the expressions has a 1 in a digit, the result has a 1 in that digit. Otherwise, the
result has a 0 in that digit.
Requirements
Version 1
See Also
JScript
expression1, expression2
Arguments
expression1
Any expression.
expression2
Any expression.
Remarks
The , operator causes the expressions on either side of it to be executed in left-to-right order, and obtains the
value of the expression on the right. The most common use for the , operator is in the increment expression of
a for loop. For example:
The for statement only allows a single expression to be executed at the end of every pass through a loop. The ,
operator is used to allow multiple expressions to be treated as a single expression, thereby getting around the
restriction.
Requirements
Version 1
See Also
JScript
Arguments
expression1
Any expression.
comparisonoperator
Any comparison operator.
expression2
Any expression.
Remarks
When comparing strings, JScript uses the Unicode character value of the string expression.
The following describes how the different groups of operators behave depending on the types and values of
expression1 and expression2:
• If the types of the two expressions are different, attempt to convert them to string, number, or
Boolean.
• NaN is not equal to anything including itself.
• Negative zero equals positive zero.
• null equals both null and undefined.
• Values are considered equal if they are identical strings, numerically equivalent numbers, the same
object, identical Boolean values, or (if different types) they can be coerced into one of these
situations.
• Every other comparison is considered unequal.
These operators behave identically to the equality operators except no type conversion is done, and the types
must be the same to be considered equal.
Requirements
Version 1
Comparison Operators 1
2 Comparison Operators
See Also
JScript
2 Comparison Operators
Conditional (Ternary) Operator (?:)
Executes one of two statements depending on a condition.
Arguments
test
Any Boolean expression.
statement1
A statement executed if test is true. May be a compound statement.
statement2
A statement executed if test is false. May be a compound statement.
Remarks
The ?: operator is a shortcut for an if...else statement. It is typically used as part of a larger expression where
an if...else statement would be awkward. For example:
The example creates a string containing "Good evening." if it is after 6pm. The equivalent code using an
if...else statement would look as follows:
Requirements
Version 1
See Also
JScript
delete expression
The expression argument is a valid JScript expression that usually results in a property name or array element.
Remarks
If the result of expression is an object, the property specified in expression exists, and the object will not allow
it to be deleted, false is returned.
Requirements
Version 3
See Also
JScript
delete Operator 1
2 delete Operator
2 delete Operator
Division Assignment Operator (/=)
Divides the value of a variable by the value of an expression and assigns the result to the variable.
result /= expression
Arguments
result
Any numeric variable.
expression
Any numeric expression.
Remarks
Requirements
Version 1
See Also
JScript
Syntax 1
result = ++variable
result = --variable
result = variable++
result = variable--
Syntax 2
++variable
--variable
variable++
variable--
Arguments
result
Any variable.
variable
Any variable.
Remarks
The increment and decrement operators are used as a shortcut to modify the value stored in a variable. The
value of an expression containing one of these operators depends on whether the operator comes before or
after the variable:
var j, k;
k = 2;
j = ++k;
j is assigned the value 3, as the increment occurs before the expression is evaluated.
var j, k;
k = 2;
j = k++;
Here, j is assigned the value 2, as the increment occurs after the expression is evaluated.
Requirements
Version 1
See Also
JScript
Arguments
result
Required. Any variable.
object
Required. Any object expression.
class
Required. Any defined object class.
Remarks
The instanceof operator returns true if object is an instance of class. It returns false if object is not an
instance of the specified class, or if object is null.
Example
function objTest(obj){
var i, t, s = ""; // Create variables.
t = new Array(); // Create an array.
t["Date"] = Date; // Populate the array.
t["Object"] = Object;
t["Array"] = Array;
for (i in t)
{
if (obj instanceof t[i]) // Check class of obj.
{
s += "obj is an instance of " + i + "\n";
}
else
{
s += "obj is not an instance of " + i + "\n";
}
}
return(s); // Return string.
}
Requirements
Version 5
See Also
instanceof Operator 1
2 instanceof Operator
JScript
2 instanceof Operator
Left Shift Assignment Operator (<<=)
Left shifts the value of a variable by the number of bits specified in the value of an expression and assigns the
result to the variable.
Arguments
result
Any variable.
expression
Any expression.
Remarks
The <<= operator shifts the bits of result left by the number of bits specified in expression. For example:
var temp
temp = 14
temp <<= 2
The variable temp has a value of 56 because 14 (00001110 in binary) shifted left two bits equals 56
(00111000 in binary). Bits are filled in with zeroes when shifting.
Requirements
Version 1
See Also
<< Operator | >> Operator | >>> Operator | Operator Precedence | Operator Summary
JScript
result %= expression
Arguments
result
Any variable.
expression
Any numeric expression.
Remarks
Requirements
Version 1
See Also
JScript
Arguments
result
Any variable.
number1
Any numeric expression.
number2
Any numeric expression.
Remarks
The modulus, or remainder, operator divides number1 by number2 (rounding floating-point numbers to
integers) and returns only the remainder as result. For example, in the following expression, A (which is
result) equals 5.
A = 19 % 6.7
Requirements
Version 1
See Also
JScript
result *= expression
Arguments
result
Any variable.
expression
Any expression.
Remarks
Requirements
Version 1
See Also
JScript
result = number1*number2
Arguments
result
Any variable.
number1
Any expression.
number2
Any expression.
Requirements
Version 1
See Also
JScript
new constructor[(arguments)]
Arguments
constructor
Required. Object's constructor. The parentheses can be omitted if the construc
Remarks
Requirements
Version 1
See Also
function Statement
JScript
new Operator 1
2 new Operator
2 new Operator
Right Shift Assignment Operator (>>=)
Right shifts the value of a variable by the number of bits specified in the value of an expression, maintaining
the sign, and assigns the result to the variable.
Arguments
result
Any variable.
expression
Any expression.
Remarks
The >>= operator shifts the bits of result right by the number of bits specified in expression. The sign bit of
result is used to fill the digits from the left. Digits shifted off the right are discarded. For example, after the
following code is evaluated, temp has a value of -4: 14 (11110010 in binary) shifted right two bits equals -4
(11111100 in binary).
var temp
temp = -14
temp >>= 2
Requirements
Version 1
See Also
<< Operator | >> Operator | >>> Operator | Operator Precedence | Operator Summary
JScript
result -= expression
Arguments
result
Any numeric variable.
expression
Any numeric expression.
Remarks
Requirements
Version 1
See Also
JScript
typeof[(]expression[)] ;
The expression argument is any expression for which type information is sought.
Remarks
The typeof operator returns type information as a string. There are six possible values that typeof returns:
"number," "string," "boolean," "object," "function," and "undefined."
Requirements
Version 1
See Also
JScript
typeof Operator 1
2 typeof Operator
2 typeof Operator
Unsigned Right Shift Operator (>>>)
Right shifts the bits of an expression, without maintaining sign.
Arguments
result
Any variable.
expression1
Any expression.
expression2
Any expression.
Remarks
The >>> operator shifts the bits of expression1 right by the number of bits specified in expression2. Zeroes
are filled in from the left. Digits shifted off the right are discarded. For example:
var temp
temp = -14 >>> 2
The variable temp has a value of 1073741820 as -14 (11111111 11111111 11111111 11110010 in binary)
shifted right two bits equals 1073741820 (00111111 11111111 11111111 11111100 in binary).
Requirements
Version 1
See Also
>>>= Operator | << Operator | >> Operator | Operator Precedence | Operator Summary
JScript
Arguments
result
Any variable.
expression
Any expression.
Remarks
Using the >>>= operator is exactly the same as doing the following:
The >>>= operator shifts the bits of result right by the number of bits specified in expression. Zeroes are
filled in from the left. Digits shifted off the right are discarded. For example:
var temp
temp = -14
temp >>>= 2
The variable temp has a value of 1073741820 as -14 (11111111 11111111 11111111 11110010 in binary)
shifted right two bits equals 1073741820 (00111111 11111111 11111111 11111100 in binary).
Requirements
Version 1
See Also
>>> Operator | << Operator | >> Operator | Operator Precedence | Operator Summary
JScript
void expression
Remarks
The void operator evaluates its expression, and returns undefined. It is most useful in situations where you
want an expression evaluated but do not want the results visible to the remainder of the script.
Requirements
Version 2
See Also
JScript
void Operator 1
2 void Operator
2 void Operator
0...n Properties
Returns the actual value of individual arguments from an arguments object returned by the arguments
property of an executing function.
[function.]arguments[[0|1|2|...|n]]
Arguments
function
Optional. The name of the currently executing Function object.
0, 1, 2,
, n
Required. Non-negative integer in the range of 0 to n where 0 represents the first argument and n
represents the final argument. The value of the final argument n is arguments.length-1.
Remarks
The values returned by the 0 . . . n properties are the actual values passed to the executing function. While not
actually an array of arguments, the individual arguments that comprise the arguments object are accessed the
same way that array elements are accessed.
Example
The following example illustrates the use of the 0 . . . n properties of the arguments object. To fully
understand the example, pass one or more arguments to the function:
function ArgTest(){
var s = "";
s += "The individual arguments are: "
for (n=0; n< arguments.length; n++){
s += ArgTest.arguments[n];
s += " ";
}
return(s);
}
print(ArgTest(1, 2, "hello", new Date()));
Requirements
Version 5.5
See Also
JScript
0...n Properties 1
2 0...n Properties
2 0...n Properties
$1...$9 Properties
Returns the nine most-recently memorized portions found during pattern matching. Read-only.
RegExp.$n
Arguments
RegExp
Always the global RegExp object.
Remarks
The value of the $1...$9 properties is modified whenever a successful parenthesized match is made. Any
number of parenthesized substrings may be specified in a regular expression pattern, but only the nine most
recent can be stored.
function matchDemo(){
var s;
var re = new RegExp("d(b+)(d)","ig");
var str = "cdbBdbsbdbdz";
var arr = re.exec(str);
s = "$1 contains: " + RegExp.$1 + "\n";
s += "$2 contains: " + RegExp.$2 + "\n";
s += "$3 contains: " + RegExp.$3;
return(s);
}
Requirements
Version 1
See Also
JScript
$1...$9 Properties 1
2 $1...$9 Properties
2 $1...$9 Properties
callee Property
Returns the Function object being executed, that is, the body text of the specified Function object.
[function.]arguments.callee
The optional function argument is the name of the currently executing Function object.
Remarks
The callee property is a member of the arguments object that becomes available only when the associated
function is executing.
The initial value of the callee property is the Function object being executed. This allows anonymous
functions to be recursive.
Example
function factorial(n){
if (n <= 0)
return 1;
else
return n * arguments.callee(n - 1)
}
print(factorial(3));
Requirements
Version 5.5
See Also
JScript
callee Property 1
2 callee Property
2 callee Property
constructor Property
Specifies the function that creates an object.
object.constructor
Remarks
The constructor property is a member of the prototype of every object that has a prototype. This includes all
intrinsic JScript objects except the Global and Math objects. The constructor property contains a reference
to the function that constructs instances of that particular object. For example:
x = new String("Hi");
if (x.constructor == String)
// Do something (the condition will be true).
or
function MyFunc {
// Body of function.
}
y = new MyFunc;
if (y.constructor == MyFunc)
// Do something (the condition will be true).
Requirements
Version 2
See Also
prototype Property
Applies To: Array Object | Boolean Object | Date Object | Function Object | Math Object | Number Object |
Object Object | String Object
JScript
constructor Property 1
2 constructor Property
2 constructor Property
E Property
Returns Euler's constant, the base of natural logarithms. The E property is approximately equal to 2.718.
numVar = Math.E
Requirements
Version 1
See Also
JScript
E Property 1
2 E Property
2 E Property
index Property
Returns the character position where the first successful match begins in a searched string. Read-only.
RegExp.index
The object associated with this property is always the global RegExp object.
Remarks
The index property is zero-based. The initial value of the index property is 1. Its value changes whenever a
successful match is made.
Example
The following example illustrates the use of the index property. This function iterates a search string and
prints out the index and lastIndex values for each word in the string.
function RegExpTest(){
var ver = Number(ScriptEngineMajorVersion() + "." + ScriptEngineMinorVersion())
if (ver >= 5.5){
var src = "The rain in Spain falls mainly in the plain.";
var re = /\w+/g;
var arr;
while ((arr = re.exec(src)) != null)
print(arr.index + "-" + arr.lastIndex + "\t" + arr);
}
else{
alert("You need a newer version of JScript for this to work");
}
}
Requirements
Version 3
See Also
JScript
index Property 1
2 index Property
2 index Property
input Property ($_)
Returns the string against which a regular expression search was performed. Read-only.
RegExp.input
The object associated with this property is always the global RegExp object.
Remarks
The value of input property is modified any time the searched string is changed.
function inputDemo(){
var s;
var re = new RegExp("d(b+)(d)","ig");
var str = "cdbBdbsbdbdz";
var arr = re.exec(str);
s = "The string used for the match was " + RegExp.input;
return(s);
}
Requirements
Version 3
See Also
JScript
[function.]arguments.length
The optional function argument is the name of the currently executing Function object.
Remarks
The length property of the arguments object is initialized by the scripting engine to the actual number of
arguments passed to a Function object when execution begins in that function.
Example
The following example illustrates the use of the length property of the arguments object. To fully understand
the example, pass more arguments to the function than the 2 arguments expected:
Requirements
Version 5.5
See Also
JScript
numVar = arrayObj.length
Arguments
numVar
Required. Any numeric variable.
arrayObj
Required. Any Array object.
Remarks
As the elements in an array do not have to be contiguous, the length property is not necessarily the number of
elements in the array. For example, in the following array definition, my_array.length contains 7, not 2:
If a value smaller than its previous value is assigned to the length property, the array is truncated, and any
elements with array indexes equal to or greater than the new value of the length property are lost.
If a value larger than its previous value is assigned to the length property, the array is expanded, and any new
elements created have the value undefined.
function LengthDemo(){
var a;
a = new Array(0,1,2,3,4);
return(a.length);
}
Requirements
Version 2
See Also
JScript
functionName.length
Remarks
The length property of a function is initialized by the scripting engine to the number of arguments in the
function's definition when an instance of the function is created.
What happens when a function is called with a number of arguments different from the value of its length
property depends on the function.
Requirements
Version 2
See Also
JScript
strVariable.length
"String Literal".length
Remarks
The length property contains an integer that indicates the number of characters in the String object. The last
character in the String object has an index of length - 1.
Requirements
Version 1
See Also
length Property (Array) | length Property (Function) | String Object Methods | String Object Properties
JScript
numVar = Math.LN10
Remarks
Requirements
Version 1
See Also
JScript
LN10 Property 1
2 LN10 Property
2 LN10 Property
LN2 Property
Returns the natural logarithm of 2.
numVar = Math.LN2
Syntax
Requirements
Version 1
See Also
JScript
LN2 Property 1
2 LN2 Property
2 LN2 Property
LOG10E Property
Returns the base-10 logarithm of e, Euler's constant.
varName = Math.LOG10E
Remarks
Requirements
Version 1
See Also
JScript
LOG10E Property 1
2 LOG10E Property
2 LOG10E Property
LOG2E Property
Returns the base-2 logarithm of e, Euler's constant.
varName = Math.LOG2E
Remarks
Requirements
Version 1
See Also
JScript
LOG2E Property 1
2 LOG2E Property
2 LOG2E Property
PI Property
Returns the ratio of the circumference of a circle to its diameter, approximately 3.141592653589793.
numVar = Math.PI
Syntax
Requirements
Version 1
See Also
JScript
PI Property 1
2 PI Property
2 PI Property
prototype Property
Returns a reference to the prototype for a class of objects.
objectName.prototype
Remarks
Use the prototype property to provide a base set of functionality to a class of objects. New instances of an
object "inherit" the behavior of the prototype assigned to that object.
For example, say you want to add a method to the Array object that returns the value of the largest element of
the array. To do this, declare the function, add it to Array.prototype, and then use it.
function array_max( ){
var i, max = this[0];
for (i = 1; i < this.length; i++)
{
if (max < this[i])
max = this[i];
}
return max;
}
Array.prototype.max = array_max;
var x = new Array(1, 2, 3, 4, 5, 6);
var y = x.max( );
After this code is executed, y contains the largest value in the array x, or 6.
All intrinsic JScript objects have a prototype property that is read-only. Functionality may be added to the
prototype, as in the example, but the object may not be assigned a different prototype. However, user-defined
objects may be assigned a new prototype.
The method and property lists for each intrinsic object in this language reference indicate which ones are part
of the object's prototype, and which are not.
Requirements
Version 2
See Also
constructor Property
Applies To: Array Object | Boolean Object | Date Object | Function Object | Number Object | Object Object |
String Object
JScript
prototype Property 1
2 prototype Property
2 prototype Property
source Property
Returns a copy of the text of the regular expression pattern. Read-only.
rgExp.source
The rgExp argument is a Regular expression object. It can be a variable name or a literal.
Requirements
Version 3
See Also
Regular Expression Object Methods | Regular Expression Object Properties | Regular Expression Syntax
JScript
source Property 1
2 source Property
2 source Property
SQRT1_2 Property
Returns he square root of 0.5, or one divided by the square root of 2.
numVar = Math.SQRT1_2
Remarks
Requirements
Version 1
See Also
JScript
SQRT1_2 Property 1
2 SQRT1_2 Property
2 SQRT1_2 Property
SQRT2 Property
Returns the square root of 2.
numVar = Math.SQRT2
Syntax
Requirements
Version 1
See Also
JScript
SQRT2 Property 1
2 SQRT2 Property
2 SQRT2 Property
undefined Property
Returns an initial value of undefined.
undefined
Remarks
The undefined property is a member of the Global object, and becomes available when the scripting engine
is initialized. When a variable has been declared but not initialized, its value is undefined.
If a variable has not been declared, you cannot compare it to undefined, but you can compare the type of the
variable to the string "undefined"
The undefined property is useful when explicitly testing or setting a variable to undefined.
Example
if (typeOf(notDeclared) == "undefined")
document.write("notDeclared has not been defined.");
Requirements
Version 5.5
See Also
JScript
undefined Property 1
2 undefined Property
2 undefined Property
@cc_on Statement
Activates conditional compilation support.
@cc_on
Remarks
It is strongly recommended that you use the @cc_on statement in a comment, so that browsers that do not
support conditional compilation will accept your script as valid syntax:
/*@cc_on*/
...
(remainder of script)
Alternatively, an @if or @set statement outside of a comment also activates conditional compilation.
Requirements
Version 3
See Also
JScript
@cc_on Statement 1
2 @cc_on Statement
2 @cc_on Statement
@if Statement
Conditionally executes a group of statements, depending on the value of an expression.
@if (
condition1
)
text1
[@elif (
condition2
)
text2]
[@else
text3]
@end
Arguments
condition1, condition2
Optional. An expression that can be coerced into a Boolean expression.
text1
Optional. Text to be parsed if condition1 is true.
text2
Optional. Text to be parsed if condition1 is false and condition2 is true.
text3
Optional. Text to be parsed if both condition1 and condition2 are false.
Remarks
When you write an @if statement, you do not have to place each clause on a separate line. You can use
multiple @elif clauses. However, all @elif clauses must come before an @else clause.
You commonly use the @if statement to determine which text among several options should be used for text
output. For example:
alert(@if (@_win32) "using Windows NT or Windows 95" @else "using Windows 3.1" @end)
Requirements
Version 3
See Also
JScript
@if Statement 1
2 @if Statement
2 @if Statement
@set Statement
Creates variables used with conditional compilation statements.
Arguments
varname
Required. Valid JScript variable name. Must be preceded by an "@" character at all times.
term
Required. Zero or more unary operators followed by a constant, conditional compilation variable, or
parenthesized expression.
Remarks
Numeric and Boolean variables are supported for conditional compilation. Strings are not. Variables created
using @set are generally used in conditional compilation statements, but can be used anywhere in JScript
code.
@set @myvar1 = 12
•! ~
•* / %
•+ -
• << >> >>>
• < <= > >=
• == != === !==
•& ^ |
• && | |
If a variable is used before it has been defined, its value is NaN. NaN can be checked for using the @if
statement:
This works because NaN is the only value not equal to itself.
Requirements
Version 3
See Also
@set Statement 1
2 @set Statement
JScript
2 @set Statement
break Statement
Terminates the current loop, or if in conjunction with a label, terminates the associated statement.
break [label];
The optional label argument specifies the label of the statement you are breaking from.
Remarks
You typically use the break statement in switch statements and while, for, for...in, or do...while loops. You
most commonly use the label argument in switch statements, but it can be used in any statement, whether
simple or compound.
Executing the break statement exits from the current loop or statement, and begins script execution with the
statement immediately following.
Example
function BreakTest(breakpoint){
var i = 0;
while (i < 100)
{
if (i == breakpoint)
break;
i++;
}
return(i);
}
Requirements
Version 1
See Also
continue Statement | do...while Statement | for Statement | for...in Statement | Labeled Statement | while
Statement
JScript
break Statement 1
2 break Statement
2 break Statement
Comment Statements
Causes comments to be ignored by the JScript parser.
Syntax 1
Single-line Comment:
// comment
Syntax 2
Multiline Comment:
/*
comment
*/
The comment argument is the text of any comment you want to include in your script.
Syntax 3
//@CondStatement
Syntax 4
/*@
condStatement
@*/
Remarks
Use comments to keep parts of a script from being read by the JScript parser. You can use comments to
include explanatory remarks in a program.
If Syntax 1 is used, the parser ignores any text between the comment marker and the end of the line. If Syntax
2 is used, it ignores any text between the beginning and end markers.
Syntaxes 3 and 4 are used to support conditional compilation while retaining compatibility with browsers that
do not support that feature. These browsers treat those forms of comments as syntaxes 1 and 2 respectively.
Example
The following example illustrates the most common uses of the comment statement.
Comment Statements 1
2 Comment Statements
Requirements
Version 1
JScript
2 Comment Statements
continue Statement
Stops the current iteration of a loop, and starts a new iteration.
continue [label];
The optional label argument specifies the statement to which continue applies.
Remarks
You can use the continue statement only inside a while, do...while, for, or for...in loop. Executing the
continue statement stops the current iteration of the loop and continues program flow with the beginning of
the loop. This has the following effects on the different types of loops:
• while and do...while loops test their condition, and if true, execute the loop again.
• for loops execute their increment expression, and if the test expression is true, execute the loop again.
• for...in loops proceed to the next field of the specified variable and execute the loop again.
Example
function skip5(){
var s = "", i=0;
while (i < 10)
{
i++;
// Skip 5
if (i==5)
{
continue;
}
s += i;
}
return(s);
}
Requirements
Version 1
See Also
break Statement | do...while Statement | for Statement | for...in Statement | Labeled Statement | while
Statement
JScript
continue Statement 1
2 continue Statement
2 continue Statement
do...while Statement
Executes a statement block once, and then repeats execution of the loop until a condition expression evaluates
to false.
do
statement
while (expression) ;
Arguments
statement
Optional. The statement to be executed if expression is true. Can be a compound statement.
expression
Optional. An expression that can be coerced to Boolean true or false. If expression is true, the loop is
executed again. If expression is false, the loop is terminated.
Remarks
The value of expression is not checked until after the first iteration of the loop, guaranteeing that the loop is
executed at least once. Thereafter, it is checked after each succeeding iteration of the loop.
Example
The following example illustrates the use of the do...while statement to iterate the Drives collection.
function GetDriveList(){
var fso, s, n, e, x;
fso = new ActiveXObject("Scripting.FileSystemObject");
e = new Enumerator(fso.Drives);
s = "";
do
{
x = e.item();
s = s + x.DriveLetter;
s += " - ";
if (x.DriveType == 3)
n = x.ShareName;
else if (x.IsReady)
n = x.VolumeName;
else
n = "[Drive not ready]";
s += n + "<br>";
e.moveNext();
}
while (!e.atEnd());
return(s);
}
Requirements
Version 3
See Also
break Statement | continue Statement | for Statement | for...in Statement | while Statement | Labeled Statement
do...while Statement 1
2 do...while Statement
JScript
2 do...while Statement
for Statement
Executes a block of statements for as long as a specified condition is true.
Arguments
initialization
Required. An expression. This expression is executed only once, before the loop is executed.
test
Required. A Boolean expression. If test is true, statement is executed. If test if false, the loop is
terminated.
increment
Required. An expression. The increment expression is executed at the end of every pass through the
loop.
statements
Optional. One or more statements to be executed if test is true. Can be a compound statement.
Remarks
You usually use a for loop when the loop is to be executed a specific number of times.
Example
Requirements
Version 1
See Also
JScript
for Statement 1
2 for Statement
2 for Statement
for...in Statement
Executes one or more statements for each property of an object, or each element of an array.
Arguments
variable
Required. A variable that can be any property of object or any element of an array.
object, array
Optional. An object or array over which to iterate.
statements
Optional. One or more statements to be executed for each property of object or each element of array.
Can be a compound statement.
Remarks
Before each iteration of a loop, variable is assigned the next property of object or the next element of array.
You can then use it in any of the statements inside the loop, exactly as if you were using the property of object
or the element of array.
When iterating over an object, there is no way to determine or control the order in which the members of the
object are assigned to variable. Iterating through an array will be performed in element order, that is, 0, 1, 2,
...
Example
The following example illustrates the use of the for ... in statement with an object used as an associative array.
function ForInDemo(){
// Create some variables.
var a, key, s = "";
// Initialize object.
a = {"a" : "Athens" , "b" : "Belgrade", "c" : "Cairo"}
// Iterate the properties.
for (key in a) {
s += a[key] + "<BR>";
}
return(s);
}
Requirements
Version 5
See Also
for...in Statement 1
2 for...in Statement
JScript
2 for...in Statement
function Statement
Declares a new function.
Arguments
functionname
Required. The name of the function.
arg1...argN
Optional. An optional, comma-separated list of arguments the function understands.
statements
Optional. One or more JScript statements.
Remarks
Use the function statement to declare a function for later use. The code contained in statements is not
executed until the function is called from elsewhere in the script.
Example
Note When calling a function, ensure that you always include the parentheses and any
required arguments. Calling a function without parentheses causes the text of the function to
be returned instead of the results of the function.
Requirements
Version 1
See Also
new Operator
JScript
function Statement 1
2 function Statement
2 function Statement
if...else Statement
Conditionally executes a group of statements, depending on the value of an expression.
if (condition)
statement1
[else
statement2]
Arguments
condition
Required. A Boolean expression. If condition is null or undefined, condition is treated as false.
statement1
Optional. The statement to be executed if condition is true. Can be a compound statement.
statement2
Optional. The statement to be executed if condition is false. Can be a compound statement.
Remarks
It is generally good practice to enclose statement1 and statement2 in braces ({}) for clarity and to avoid
inadvertent errors.
Example
In the following example, you may intend that the else be used with the first if statement, but it is used with
the second one.
if (x == 5)
if (y == 6)
z = 17;
else
z = 20;
if (x == 5)
{
if (y == 6)
z = 17;
}
else
z = 20;
Similarly, if you want to add a statement to statement1, and you don not use braces, you can accidentally
create an error:
if (x == 5)
z = 7;
q = 42;
else
z = 19;
In this case, there is a syntax error, because there is more than one statement between the if and else
statements. Braces are required around the statements between if and else.
if...else Statement 1
2 if...else Statement
Requirements
Version 1
See Also
JScript
2 if...else Statement
Labeled Statement
Provides an identifier for a statement.
label :
statements
Arguments
label
Required. A unique identifier used when referring to the labeled statement.
statements
Optional. One or more statements associated with label.
Remarks
Labels are used by the break and continue statements to specify the statement to which the break and
continue apply.
Example
In the following statement the continue statement uses a labeled statement to create an array in which the
third column of each row contains and undefined value:
function labelDemo(){
var a = new Array();
var i, j, s = "", s1 = "";
Outer:
for (i = 0; i < 5; i++)
{
Inner:
for (j = 0; j < 5; j++)
{
if (j == 2)
continue Inner;
else
a[i,j] = j + 1;
}
}
for (i = 0;i < 5; i++)
{
s = ""
for (j = 0; j < 5; j++)
{
s += a[i,j];
}
s1 += s + "\n";
}
return(s1)
}
Requirements
Version 3
See Also
Labeled Statement 1
2 Labeled Statement
JScript
2 Labeled Statement
return Statement
Exits from the current function and returns a value from that function.
return[(][expression][)];
The optional expression argument is the value to be returned from the function. If omitted, the function does
not return a value.
Remarks
You use the return statement to stop execution of a function and return the value of expression. If expression
is omitted, or no return statement is executed from within the function, the expression that called the current
function is assigned the value undefined.
Example
Requirements
Version 1
See Also
function Statement
JScript
return Statement 1
2 return Statement
2 return Statement
switch Statement
Enables the execution of one or more statements when a specified expression's value matches a label.
switch (expression) {
case label :
statementlist
case label :
statementlist
...
default :
statementlist
}
Arguments
expression
The expression to be evaluated.
label
An identifier to be matched against expression. If label === expression, execution starts with the
statementlist immediately after the colon, and continues until it encounters either a break statement,
which is optional, or the end of the switch statement.
statementlist
One or more statements to be executed.
Remarks
Use the default clause to provide a statement to be executed if none of the label values matches expression. It
can appear anywhere within the switch code block.
Zero or more label blocks may be specified. If no label matches the value of expression, and a default case is
not supplied, no statements are executed.
Example
function MyObject() {
...}
switch (object.constructor){
case Date:
...
case Number:
...
case String:
...
case MyObject:
...
switch Statement 1
2 switch Statement
default:
...
}
Requirements
Version 3
See Also
JScript
2 switch Statement
this Statement
Refers to the current object.
this.property
Remarks
The this keyword is typically used in object constructors to refer to the current object.
Example
In the following example, this refers to the newly created Car object, and assigns values to three properties:
For client versions of JScript, this refers to the window object if used outside of the context of any other
object.
Requirements
Version 1
See Also
new Operator
JScript
this Statement 1
2 this Statement
2 this Statement
try...catch
finally Statement
Implements error handling for JScript.
try {
tryStatements}
catch(exception){
catchStatements}
finally {
finallyStatements}
Arguments
tryStatements
Required. Statements where an error can occur.
exception
Required. Any variable name. The initial value of exception is the value of the thrown error.
catchStatements
Optional. Statements to handle errors occurring in the associated tryStatements.
finallyStatements
Optional. Statements that are unconditionally executed after all other error processing has occurred.
Remarks
The try...catch
finally statement provides a way to handle some or all of the possible errors that may occur
in a given block of code, while still running code. If errors occur that the programmer has not handled, JScript
simply provides its normal error message to a user, as if there was no error handling.
The tryStatements contain code where an error can occur, while catchStatements contain the code to handle
any error that does occur. If an error occurs in the tryStatements, program control is passed to catchStatements
for processing. The initial value of exception is the value of the error that occurred in tryStatements. If no
error occurs, catchStatements are never executed.
If the error cannot be handled in the catchStatements associated with the tryStatements where the error
occurred, use the throw statement to propagate, or rethrow, the error to a higher-level error handler.
After all statements in tryStatements have been executed and any error handling has occurred in
catchStatements, the statements in finallyStatements are unconditionally executed.
Notice that the code inside finallyStatements is executed even if a return statement occurs inside the try or
catch blocks, or if the catch block re-throws the error. finallyStatments are guaranteed to always run, unless
an unhandled error occurs (for example, causing a run-time error inside the catch block).
Example
try {
print("Outer try running..");
try {
print("Nested try running...");
throw "an error";
}
catch(e) {
print("Nested catch caught " + e);
throw e + " re-thrown";
}
try...catch
finally Statement 1
2 try...catch
finally Statement
finally {
print("Nested finally is running...");
}
}
catch(e) {
print("Outer catch caught " + e);
}
finally {
print("Outer finally running");
}
// Change this for Windows Script Host to say WScript.Echo(s)
function print(s){
document.write(s);
}
Requirements
Version 5
See Also
throw Statement
JScript
2 try...catch
finally Statement
var Statement
Declares a variable.
Arguments
variable1, variable2
The names of the variables being declared.
value1, value2
The initial value assigned to the variable.
Remarks
Use the var statement to declare variables. These variables can be assigned values at declaration or later in
your script.
Example
var index;
var name = "Thomas Jefferson";
var answer = 42, counter, numpages = 10;
Requirements
Version 1
See Also
JScript
var Statement 1
2 var Statement
2 var Statement
while Statement
Executes a statement until a specified condition is false.
while (expression)
statements
Arguments
expression
Required. A Boolean expression checked before each iteration of the loop. If expression is true, the
loop is executed. If expression is false, the loop is terminated.
statements
Optional. One or more statements to be executed if expression is true.
Remarks
The while statement checks expression before a loop is first executed. If expression is false at this time, the
loop is never executed.
Example
function BreakTest(breakpoint){
var i = 0;
while (i < 100)
{
if (i == breakpoint)
break;
i++;
}
return(i);
}
Requirements
Version 1
See Also
break Statement | continue Statement | do...while Statement | for Statement | for...in Statement
JScript
while Statement 1
2 while Statement
2 while Statement
with Statement
Establishes the default object for a statement.
with (object)
statements
Arguments
object
The new default object.
statements
One or more statements for which object is the default object.
Remarks
The with statement is commonly used to shorten the amount of code that you have to write in certain
situations. In the example that follows, notice the repeated use of Math.
When you use the with statement, your code becomes shorter and easier to read:
with (Math){
x = cos(3 * PI) + sin (LN10)
y = tan(14 * E)
}
Requirements
Version 1
See Also
this Statement
with Statement 1
2 with Statement
2 with Statement
VBScript User's Guide
What Is VBScript?
VBScript Fundamentals
VBScript Variables
VBScript Constants
VBScript Operators
VBScript Procedures
<SCRIPT LANGUAGE="VBScript">
<!--
Function CanDeliver(Dt)
CanDeliver = (CDate(Dt) - Now()) > 2
End Function
-->
</SCRIPT>
Beginning and ending <SCRIPT> tags surround the code. The LANGUAGE attribute indicates the scripting
language. You must specify the language because browsers can use other scripting languages. Notice that the
CanDeliver function is embedded in comment tags (<! and >). This prevents browsers that don't
understand the <SCRIPT> tag from displaying the code.
Since the example is a general function it is not tied to any particular form control you can include it in
the HEAD section of the page:
<HTML>
<HEAD>
<TITLE>Place Your Order</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
Function CanDeliver(Dt)
CanDeliver = (CDate(Dt) - Now()) > 2
End Function
-->
</SCRIPT>
</HEAD>
<BODY>
...
You can use SCRIPT blocks anywhere in an HTML page. You can put them in both the BODY and HEAD
sections. However, you will probably want to put all general-purpose scripting code in the HEAD section in
order to keep all the code together. Keeping your code in the HEAD section ensures that all code is read and
decoded before it is called from within the BODY section.
One notable exception to this rule is that you may want to provide inline scripting code within forms to
respond to the events of objects in your form. For example, you can embed scripting code to respond to a
button click in a form:
<HTML>
<HEAD>
<TITLE>Test Button Events</TITLE>
</HEAD>
<BODY>
<FORM NAME="Form1">
<INPUT TYPE="Button" NAME="Button1" VALUE="Click">
<SCRIPT FOR="Button1" EVENT="onClick" LANGUAGE="VBScript">
MsgBox "Button Pressed!"
</SCRIPT>
</FORM>
Most of your code will appear in either Sub or Function procedures and will be called only when specified by
your code. However, you can write VBScript code outside procedures, but still within a SCRIPT block. This
code is executed only once, when the HTML page loads. This allows you to initialize data or dynamically
change the look of your Web page when it loads.
With Microsoft® Internet Explorer, you can view the page produced by the following HTML code. If you
click the button on the page, you see VBScript in action.
<HTML>
<HEAD><TITLE>A Simple First Page</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Button1_OnClick
MsgBox "Mirabile visu."
End Sub
-->
</SCRIPT>
</HEAD>
<BODY>
<H3>A Simple First Page</H3><HR>
<FORM><INPUT NAME="Button1" TYPE="BUTTON" VALUE="Click Here"></FORM>
</BODY>
</HTML>
The result is a little underwhelming: a dialog box displays a Latin phrase ("Wonderful to behold"). However,
there's quite a bit going on.
When Internet Explorer reads the page, it finds the <SCRIPT> tags, recognizes there is a piece of VBScript
code, and saves the code. When you click the button, Internet Explorer makes the connection between the
button and the code, and runs the procedure.
The Sub procedure in the <SCRIPT> tags is an event procedure. There are two parts to the procedure name:
the name of the button, Button1 (from the NAME attribute in the <INPUT> tag), and an event name,
OnClick. The two names are joined by an underscore(_). Any time the button is clicked, Internet Explorer
looks for and runs the corresponding event procedure, Button1_OnClick.
Internet Explorer defines the events available for form controls in the Internet Explorer Scripting Object
Model documentation, which can be found on the Microsoft® Web site (http://www.microsoft.com).
Pages can use combinations of controls and procedures, too. VBScript and Forms shows some simple
interactions between controls.
Although the preceding way is probably the simplest and most general, you can attach VBScript code to
events in two other ways. Internet Explorer allows you to add short sections of inline code in the tag defining
the control. For example, the following <INPUT> tag performs the same action as the previous code example
when you click the button:
Notice that the function call itself is enclosed in single quotation marks, and the string for the MsgBox
function is enclosed in double quotation marks. You can use multiple statements as long as you separate the
statements with colons (:).
You can also write a <SCRIPT> tag so that it applies only to a particular event for a specific control:
Because the <SCRIPT> tag already specifies the event and the control, you don't use Sub and End Sub
statements.
You can use Visual Basic Scripting Edition to do much of the form processing that you'd usually have to do
on a server. You can also do things that just can't be done on the server.
Here's an example of simple client-side validation. The HTML code is for a text box and a button. If you use
Microsoft® Internet Explorer to view the page produced by the following code, you'll see a small text box
with a button next to it.
<HTML>
<HEAD><TITLE>Simple Validation</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Validate
Dim TheForm
Set TheForm = Document.forms("ValidForm")
If IsNumeric(TheForm.Text1.Value) Then
If TheForm.Text1.Value < 1 Or TheForm.Text1.Value > 10 Then
MsgBox "Please enter a number between 1 and 10."
Else
MsgBox "Thank you."
End If
Else
MsgBox "Please enter a numeric value."
End If
End Sub-->
</SCRIPT>
</HEAD>
<BODY>
<H3>Simple Validation</H3><HR>
<form id="ValidForm" action="nothing.asp" onsubmit="Validate(); return false;" language="jscript"
Enter a value between 1 and 10:
<input name="Text1" TYPE="TEXT" SIZE="2">
<input name="Submit" TYPE="Submit" VALUE="Submit">
</form>
</BODY>
</HTML>
The difference between this text box and the examples on A Simple VBScript Page is that the Value property
of the text box is used to check the entered value. To get the Value property, the code has to qualify the
reference to the name of the text box.
You can always write out the full reference Document.ValidForm.Text1. However, where you have
multiple references to form controls, you'll want to do what was done here. First declare a variable. Then use
the Set statement to assign the form to the variable TheForm. A regular assignment statement, such as Dim,
doesn't work here; you must use Set to preserve the reference to an object.
Notice that the example directly tests the value against a number: it uses the IsNumeric function to make sure
the string in the text box is a number. Although VBScript automatically converts strings and numbers, it's
always a good practice to test a user-entered value for its data subtype and to use conversion functions as
necessary. When doing addition with text box values, convert the values explicitly to numbers because the
plus sign (+) operator represents both addition and string concatenation. For example, if Text1 contains "1"
and Text2 contains "2", you see the following results:
The simple validation example uses a plain button control. If a Submit control was used, the example would
never see the data to check it everything would go immediately to the server. Avoiding the Submit control
lets you check the data, but it doesn't submit the data to the server. That requires an additional line of code:
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Button1_OnClick
Dim TheForm
Set TheForm = Document.ValidForm
If IsNumeric(TheForm.Text1.Value) Then
If TheForm.Text1.Value < 1 Or TheForm.Text1.Value > 10 Then
MsgBox "Please enter a number between 1 and 10."
Else
MsgBox "Thank you."
TheForm.Submit ' Data correct; send to server.
End If
Else
MsgBox "Please enter a numeric value."
End If
End Sub
-->
</SCRIPT>
To send the data to the server, the code invokes the Submit method on the form object when the data is
correct. From there, the server handles the data just as it otherwise would except that the data is correct
before it gets there. Find complete information about the Submit method and other methods in the Internet
Explorer Scripting Object Model documentation, which can be found on the Microsoft® Web site
(http://www.microsoft.com).
So far, you've seen only the standard HTML <FORM> objects. Internet Explorer also lets you exploit the full
power of ActiveX® controls (formerly called OLE controls) and Java objects.
Whether you use an ActiveX® control (formerly called an OLE control) or a Java object, Microsoft Visual
Basic Scripting Edition and Microsoft® Internet Explorer handle it the same way. If you're using Internet
Explorer and have installed the Label control, you can see the page produced by the following code.
You include an object using the <OBJECT> tags and set its initial property values using <PARAM> tags. If
you're a Visual Basic programmer, you'll recognize that using the <PARAM> tags is just like setting initial
properties for a control on a form. For example, the following set of <OBJECT> and <PARAM> tags adds the
ActiveX Label control to a page:
<OBJECT
classid="clsid:99B42120-6EC7-11CF-A6C7-00AA00A47DD2"
id=lblActiveLbl
width=250
height=250
align=left
hspace=20
vspace=0
>
<PARAM NAME="Angle" VALUE="90">
<PARAM NAME="Alignment" VALUE="4">
<PARAM NAME="BackStyle" VALUE="0">
<PARAM NAME="Caption" VALUE="A Simple Desultory Label">
<PARAM NAME="FontName" VALUE="Verdana, Arial, Helvetica">
<PARAM NAME="FontSize" VALUE="20">
<PARAM NAME="FontBold" VALUE="1">
<PARAM NAME="FrColor" VALUE="0">
</OBJECT>
You can get properties, set properties, and invoke methods just as with any of the form controls. The
following code, for example, includes <FORM> controls you can use to manipulate two properties of the
Label control:
<FORM NAME="LabelControls">
<INPUT TYPE="TEXT" NAME="txtNewText" SIZE=25>
<INPUT TYPE="BUTTON" NAME="cmdChangeIt" VALUE="Change Text">
<INPUT TYPE="BUTTON" NAME="cmdRotate" VALUE="Rotate Label">
</FORM>
With the form defined, an event procedure for the cmdChangeIt button changes the label text:
<SCRIPT LANGUAGE="VBScript">
<!--
Sub cmdChangeIt_onClick
Dim TheForm
Set TheForm = Document.LabelControls
lblActiveLbl.Caption = TheForm.txtNewText.Value
End Sub
-->
</SCRIPT>
The code qualifies references to controls and values inside the forms just as in the Simple Validation example.
Several ActiveX controls are available for use with Internet Explorer. You can find complete information
about the properties, methods, and events there, as well as the class identifiers (CLSID) for the controls on the
Microsoft® Web site (http://www.microsoft.com). You can find more information about the <OBJECT> tag
on the Internet Explorer 4.0 Author's Guide and HTML Reference page.
Note Earlier releases of Internet Explorer required braces ({}) around the classid attribute
and did not conform to the W3C specification. Using braces with the current release generates
a "This page uses an outdated version of the <OBJECT> tag" message.
Errors
Events
Functions
Methods
Miscellaneous
Operators
Properties
Statements
object.Count
The object is always the name of one of the items in the Applies To list.
Remarks
[JScript]
function CountDemo()
{
var a, d, i, s; // Create some variables.
d = new ActiveXObject("Scripting.Dictionary");
d.Add ("a", "Athens"); // Add some keys and items.
d.Add ("b", "Belgrade");
d.Add ("c", "Cairo");
a = (new VBArray(d.Keys())); // Get the keys.
s = "";
for (i = 0; i < d.Count; i++) //Iterate the dictionary.
{
s += a.getItem(i) + " - " + d(a.getItem(i)) + "<br>";
}
return(s); // Return the results.
}
[VBScript]
Function ShowKeys
Dim a, d, i, s ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens" ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.Keys ' Get the keys.
For i = 0 To d.Count -1 ' Iterate the array.
s = s & a(i) & "<BR>" ' Create return string.
Next
ShowKeys = s
End Function
See Also
Applies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection
Count Property 1
2 Count Property
2 Count Property
Item Property
Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the
specified key. Read/write.
object.Item(key)[ = newitem]
Arguments
object
Required. Always the name of a collection or Dictionary object.
key
Required. Key associated with the item being retrieved or added.
newitem
Optional. Used for Dictionary object only; no application for collections. If provided, newitem is the
new value associated with the specified key.
Remarks
If key is not found when changing an item, a new key is created with the specified newitem. If key is not found
when attempting to return an existing item, a new key is created and its corresponding item is left empty.
[JScript]
function DicTest(keyword)
{
var a, d;
d = new ActiveXObject("Scripting.Dictionary");
d.Add("a", "Athens");
d.Add("b", "Belgrade");
d.Add("c", "Cairo");
a = d.Item(keyword);
return(a);
}
[VBScript]
Function ItemDemo
Dim d ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens" ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
ItemDemo = d.Item("c") ' Get the item.
End Function
See Also
Applies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection
Item Property 1
2 Item Property
2 Item Property
Key Property
Sets a key in a Dictionary object.
object.Key(key) = newkey
Arguments
object
Required. Always the name of a Dictionary object.
key
Required. Key value being changed.
newkey
Required. New value that replaces the specified key.
Remarks
If key is not found when changing a key, a new key is created and its associated item is left empty.
[JScript]
var d;
d = new ActiveXObject("Scripting.Dictionary");
function AddStuff()
{
var a;
d.Add("a", "Athens");
d.Add("b", "Belgrade");
d.Add("c", "Cairo");
}
See Also
Key Property 1
2 Key Property
2 Key Property
Add Method (Dictionary)
Adds a key and item pair to a Dictionary object.
Arguments
object
Required. Always the name of a Dictionary object.
key
Required. The key associated with the item being added.
item
Required. The item associated with the key being added.
Remarks
[JScript]
var d;
d = new ActiveXObject("Scripting.Dictionary");
d.Add("a", "Athens");
d.Add("b", "Belgrade");
d.Add("c", "Cairo");
[VBScript]
Dim d ' Create a variable.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens" ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
See Also
Add Method (Folders) | Exists Method | Items Method | Keys Method | Remove Method | RemoveAll Method
object.Column
Remarks
After a newline character has been written, but before any other character is written, Column is equal to 1.
[JScript]
function GetColumn()
{
var fso, f, m;
var ForReading = 1, ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true);
f.Write("Hello World!");
f.Close();
f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
m = f.ReadLine();
return(f.Column);
}
[VBScript]
Function GetColumn
Const ForReading = 1, ForWriting = 2
Dim fso, f, m
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!"
f.Close
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
m = f.ReadLine
GetColumn = f.Column
End Function
See Also
Line Property
Column Property 1
2 Column Property
2 Column Property
Line Property
Read-only property that returns the current line number in a TextStream file.
object.Line
Remarks
After a file is initially opened and before anything is written, Line is equal to 1.
[JScript]
function GetLine()
{
var fso, f, r
var ForReading = 1, ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject")
f = fso.OpenTextFile("c:\\textfile.txt", ForWriting, true)
f.WriteLine("Hello world!");
f.WriteLine("JScript is fun");
f.Close();
f = fso.OpenTextFile("c:\\textfile.txt", ForReading);
r = f.ReadAll();
return(f.Line);
}
[VBScript]
Function GetLine
Const ForReading = 1, ForWriting = 2
Dim fso, f, ra
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!" & vbCrLf & "VB Script is fun!" & vbCrLf
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
ra = f.ReadAll
GetLine = f.Line
End Function
See Also
Column Property
Line Property 1
2 Line Property
2 Line Property
Add Method (Folders)
Adds a new folder to a Folders collection.
object.Add (folderName)
Arguments
object
Required. Always the name of a Folders collection.
folderName
Required. The name of the new Folder being added.
Remarks
The following example illustrates the use of the Add method to create a new folder.
[JScript]
function AddNewFolder(path,folderName)
{
var fso, f, fc, nf;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFolder(path);
fc = f.SubFolders;
if (folderName != "" )
nf = fc.Add(folderName);
else
nf = fc.Add("New Folder");
}
[VBScript]
Sub AddNewFolder(path, folderName)
Dim fso, f, fc, nf
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(path)
Set fc = f.SubFolders
If folderName <> "" Then
Set nf = fc.Add(folderName)
Else
Set nf = fc.Add("New Folder")
End If
End Sub
See Also
object.Count
The object is always the name of one of the items in the Applies To list.
Remarks
[JScript]
function CountDemo()
{
var a, d, i, s; // Create some variables.
d = new ActiveXObject("Scripting.Dictionary");
d.Add ("a", "Athens"); // Add some keys and items.
d.Add ("b", "Belgrade");
d.Add ("c", "Cairo");
a = (new VBArray(d.Keys())); // Get the keys.
s = "";
for (i = 0; i < d.Count; i++) //Iterate the dictionary.
{
s += a.getItem(i) + " - " + d(a.getItem(i)) + "<br>";
}
return(s); // Return the results.
}
[VBScript]
Function ShowKeys
Dim a, d, i, s ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens" ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.Keys ' Get the keys.
For i = 0 To d.Count -1 ' Iterate the array.
s = s & a(i) & "<BR>" ' Create return string.
Next
ShowKeys = s
End Function
See Also
Applies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection
Count Property 1
2 Count Property
2 Count Property
Script Components
Microsoft® Windows® Script Components provide you with an easy way to create COM components using
scripting languages such as Microsoft® Visual Basic® Scripting Edition (VBScript) and Microsoft®
JScript®. Use script components as COM components in applications such as Microsoft® Internet
Information Services (IIS), Microsoft® Windows® Script Host, and any other application that can support
COM components. The areas discussed in this tutorial are shown in the following list.
• Script Components Overview Learn what script components are and how to use them.
• Creating Script Components Create a script component.
• Using Script Components Use a script component in your applications.
• Implementing ASP Script Components Create a script component that incorporates the functionality
of Active Server Pages (ASP), allowing you to isolate and reuse ASP logic.
• Implementing DHTML Behavior Script Components Create a script component that can be used in
Microsoft® Internet Explorer 5.0 to define behaviors.
Script Components 1
2 Script Components
2 Script Components
Script Components Overview
Windows® Script Components are an exciting new technology that allows you to create powerful, reusable
COM components with easy-to-use scripting languages such as Microsoft® Visual Basic® Scripting Edition
(VBScript) and Microsoft® JScript®. The following topics provide an overview of script component
technology, and explain how to create and use script components.
• Introducing Script Components Learn what script components are, and the advantages to using them.
• How Script Components Work Understand what script component technology consists of, and how
to create script components.
Note For more information about ActiveX Scripting interfaces, see the Microsoft Scripting
Technologies Web site at www.microsoft.com.
This new script component technology supports common types of COM components, such as Automation,
and is extensible with add-ons such as DHTML behaviors.
Script Components:
Using script components, you can create COM components for a variety of tasks, such as performing
middle-tier business logic, accessing and manipulating database data, adding transaction processing to
applications, and adding interactive effects to a Web page using DHTML Behaviors.
See Also
• The script component run-time (Scrobj.dll), which helps dispatch COM requests to your scripts. In
COM terms, Scrobj.dll functions as the inproc server for script components.
• Interface handlers, which are compiled components that implement specific COM interfaces.
Different interface handlers come ready to work as specific types of COM components.
The most commonly used interface handlers, including the COM Automation interface handler, an
ASP interface handler, and a handler for DHTML Behaviors, are already built into the script
component run-time. Others are available as add-on components, or embedded into specific
applications.
• Your script component file (an .wsc file). Script component files are XML (Extensible Markup
Language) files that contain information about what type of COM component you want to create (that
is, what interface handlers you want to use). Then, depending on what functionality the handler makes
available, you write script in your script component to implement those interfaces.
The script component run-time serves as an entry point for the host application. The complexities of COM,
including the implementation of such COM-standard interfaces as IUnknown, are embedded in the various
interface handlers. Your script component contains only the script required to implement the functionality of
the COM component.
For example, one of the most common types of COM components is an Automation component, which is a
component with properties and methods that can be called from other applications. The low-level COM
interfaces required to implement this functionality such as dispatching to the correct function when a
method is called are built into an Automation interface handler. In your script component file, you define
the properties, methods, and events you want to expose, and the Automation handler makes sure they are
called correctly when the host application needs them.
See Also
• <component> and <package> elements The <component> element encloses one entire script
component definition. Multiple <component> elements can appear in the same .wsc file, and are
contained within a master <package> element.
• <registration> element Includes information used to register your script component as a COM
component. This element might not be required if the host application (such as Microsoft® Internet
Explorer 5.0) does not directly use the Windows registry when creating an instance of the script
component.
• <public> element Encloses definitions for properties, methods, and events that your script
component exposes. The definitions point to variables or functions defined in a separate <script>
block.
• <implements> element Specifies the COM interface handler for the script component, which
determines what type of COM component the script component will be. For example, by specifying
<implements type=ASP>, you implement the ASP interface handler and therefore get access to the
ASP object model in your script component.
The <public> element is used to specify that a script component implements the COM Automation
interface handler. Therefore, you don't need to create an <implements> element for the Automation
handler.
Note The script component run-time includes interface handlers for Automation
(exposed using the <public> element), for ASP, and for Internet Explorer 5.0
DHTML Behaviors. Other interface handlers are available as external DLLs. For
more information about additional interface handlers and script components, see the
Microsoft Scripting Technologies Web site.
• <script> element Contains the script used to implement the logic of your script component,
depending on what type of COM component you are creating. For example, if you are creating a
COM Automation component, you declare properties, methods, and events in a <public> element, and
then write the script to define them in one or more <script> elements.
• <object> element Contains information about an object that you use in your script, such as another
COM component.
• <resource> elements Contain values that should not be hard-coded into script component code.
Resource elements can include information that might change between versions, strings that might be
translated, and other values.
• <reference> element References a type library you want to use in script.
• <comment> elements Contain text that is ignored when the script component is parsed and
executed.
Note If you are concerned that the .wsc files you create contain XML that conforms
to XML standards, you can specify that the script component's XML parser check the
XML syntax. For example, this is useful if you think you might someday use an
XML editor to work with your files. Otherwise, however, it is not usually a concern.
For more details, see Script Component Files and XML Conformance.
<?XML version="1.0"?>
<package>
<?component error="true" debug="true"?>
<comment>
This skeleton shows how script component elements are
assembled into a .wsc file.
</comment>
<component id="MyScriptlet">
<registration
progid="progID"
description="description"
version="version"
clsid="{00000000-0000-0000-000000000000}"/>
<reference object="progID">
<public>
<property name="propertyname"/>
<method name="methodname"/>
<event name="eventname"/>
</public>
<script language="VBScript">
<![CDATA[
dim propertyname
Function methodname()
' Script here.
End Function
]]>
</script>
<script language="JScript">
<![CDATA[
function get_propertyname()
{ // Script here.
}
function put_propertyname(newValue)
{ // Script here.
fireEvent(eventname)
}
]]>
</script>
Note In XML, you can specify elements without content (attributes only), such as the
<property> and <method> elements in the previous example, by closing the element with />.
Note that:
• The <?XML ?> declaration at the top indicates that this is an XML file and that it conforms to XML
protocol. This declaration is optional; if you leave it out, you can use slightly looser syntax when
creating the script component's elements. For details, see Script Component Files and XML
Conformance.
• The <package> element is optional in this example, because the file contains only one <component>
element.
• The <?component?> processing instruction includes attributes for specifying the error checking
options. For details, see Checking For Errors in Script Component Files. If you do not include this
element, the default options are all false.
• A <comment> element can appear anywhere in the script component.
• A <registration> element is not required in all cases. For example, a script component that
implements the DHTML Behaviors interface handler in Internet Explorer 5.0 does not need to be
registered, because Internet Explorer directly instantiates the behaviors as they are detected on the
page. For details about registration requirements, see the documentation for the interface handler you
are implementing, and note also which host the script component will be used in.
• A <reference> element allows you to include a type library in the script component so you can use the
library's constants in your script.
• The <public> element encloses <property>, <method>, and <event> elements. The script that defines
these appears later in the script component file.
• The <implements> element is used to make available non-default COM interfaces. For example, you
can expose the ASP interface with an <implements> type such as the following:
The exact elements that appear inside an <implements> element depend on what interface you are
implementing.
Note The <implements> element is shown here with an id attribute. However, this
attribute is optional, except in cases where you must disambiguate objects or
variables. For details, see the <implements> element.
• In this skeleton, there are two script elements, one for VBScript and one for JScript. If you are using
only one scripting language, you do not need more than one <script> element. Because the
<?XML ?> declaration appears at the top of the file, a CDATA section is required to make the script
in the <script> element opaque. For details, see Script Component Files and XML Conformance.
• The <object> element creates a reference to an object you want to use in script within the script
component.
After creating the skeleton, fill in the elements to define the script component's functionality, depending on
which interface handler you are implementing.
See Also
Checking For Errors in Script Component Files | Creating a Script Component Type Library | Creating
Registration Information | Exposing Events | Exposing Methods | Exposing Properties | Implementing ASP
Script Components | Implementing DHTML Behavior Script Components | Script Component Files and XML
Conformance | Using the Script Component Wizard
Note You can download and install the Script Component Wizard from the
Microsoft Scripting Technologies Web site on www.microsoft.com.
The wizard creates a skeleton script component with information you provide, and writes it out as an .wsc file.
Edit the .wsc file and add your script to create the script component's functionality.
Note The wizard creates a script component file containing the <?XML ?> declaration at the
top, meaning that the contents of the file must be XML-conformant. For more details, see
Script Component Files and XML Conformance.
See Also
Script Component File Contents | Creating Registration Information | Creating Script Components | Script
Component Files and XML Conformance
Note Registration is not required in every case. For example, a script component that
implements the DHTML Behaviors interface handler in Internet Explorer 5.0 does not need to
be registered, because Internet Explorer registers the behaviors as they are detected on the
page. For more details about using Behaviors, see the "Using DHTML Behaviors" topic on
the Microsoft Site Builder Network (SBN) Web site. If the host application supports
monikers, you can also create an instance of a script component without registering it.
• A program ID (prog ID), which is the name used in the host application when creating an instance of
the script component. For example, if your script component's program ID is
Component.MyComponent, you can create an instance of it in Microsoft® Visual Basic® using a
statement such as the following:
Note If you create a script component using the Script Component Wizard, the
wizard automatically creates a program ID and class ID for you. For details, see
Using The Script Component Wizard.
The registration program can create a class ID for your script component when it is registered. However, it is
highly recommended that you provide a class ID for the script component yourself, to ensure that your script
component has the same class ID on all computers on which it is registered. Allowing the registration program
to create a class ID can also cause problems if you use the script component with development tools that store
class IDs. If the registration creates a new class ID each time, it will not match the ID stored by the
application.
• Create an <registration> element that includes at least a program ID, and optionally, a class ID,
description, and version, as shown in the following example:
<registration
description="My Test Component"
progid="Component.TestScript"
version="1"
classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"/>
Note The registration attributes can appear in any order in the <registration>
element.
• In the <registration> element, include an <script> element. To run script during registration, write a
register( ) function. To run script when the script component has been unregistered, include an
unregister( ) function.
The following example shows how to post messages when the script component is registered or
unregistered.
Note A CDATA section is required to make the script in the <script> element
opaque. For details, see Script Component Files and XML Conformance.
<registration
description="My Test Component"
progid="Component.TestScript"
version="1"
classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}">
<script language="VBScript">
<![CDATA[
Function register()
MsgBox "Component 'My Test Component' registered."
End Function
Function unregister()
MsgBox "Component 'My Test Component' unregistered."
End Function
]]>
</script>
</registration>
• Include the remotable attribute in the <registration> element, as shown in the following example:
<registration
description="My Test Component"
progid="Component.TestScript"
version="1"
classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"
remotable=true/>
For more details about creating instances of a script component remotely, see Using a Script Component in an
Application.
See Also
Script Component File Contents | Using The Script Component Wizard | Creating a Script Component Type
Library | Checking For Errors in Script Component Files | Script Component Files and XML Conformance
To expose a method
For example, the following example shows a fragment from a script component file with two
methods, factorial and getRandomNumber.
Note A CDATA section is required to make the script in the <script> element
opaque. For details, see Script Component Files and XML Conformance.
<public>
<method name="factorial"/>
<method name="random" internalName="getRandomNumber">
<parameter name="upperBound"/>
<parameter name="seed"/>
</method>
</public>
<script language="VBScript">
Function factorial(n)
<![CDATA[
If isNumeric(n) Then
If n <= 1 Then
factorial = 1
Else
factorial = n*factorial(n-1)
End If
Else
factorial = -2 ' Error code.
End If
End Function
You can specify a default method for a script component so the host application can invoke the method
without explicitly calling it. For example, if you have exposed a method called factorial and marked it as the
default, you can call it in the followoing ways in Visual Basic:
To specify a default method, include an attribute assigning a special dispatch identifier (a dispid) to the
method. For more information about dispids, see Exposing Events.
Exposing Methods 1
2 Exposing Methods
• In the <method> element, include the attribute dispid="0", as shown in the following example:
<public>
<method name="factorial" dispid="0"/>
</public>
Note This technique can be used to assign either a default method or a default
property, but not both. There can be only one element in the script component with
the dispid of zero.
See Also
2 Exposing Methods
Exposing Properties
You can expose properties in two ways:
• As simple values The property is simply a global variable that can be read and written by the script
component's user. Because the value is stored in a global value, you can manipulate it in your
Windows® Script Component file's scripts.
• As functions The property is defined using a function. This allows you to calculate a property value,
and to control whether a property is read-only, read-write, or write-only.
You can also mark a property as the default value for a script component.
Note A CDATA section is required to make the script in the <script> element
opaque. For details, see Script Component Files and XML Conformance.
<public>
<property name="name"/>
<property name="tag" internalName="tagVar"/>
</public>
<script language="VBScript">
<![CDATA[
Dim name
name = "script component" ' Initializes the value of name property.
Dim tagVar
tagVar = "10" ' Initializes the value of tag property.
]]>
</script>
1. In the script component file's <public> element, include a <property> element that contains a <get>
element to define the read function and a <put> element to define the write function. If you do not
include the <put> element, the property will be read-only. If you do not include the <get> element,
the property will be write-only.
2. Write procedures in a <script> element outside the <public> element to implement the functions. The
function for setting the property's value the put function must accept a single parameter, the value
to set the property to.
The names of the procedures must match the internal names you specified in the <property> element.
If you did not specify an internalName attribute, the names of the functions must be the name of the
function with the get_ prefix for a read function, and with a put_ prefix for the write function.
3. For example, the following script component fragment is an example of a script component file that
exposes three properties: sname, dateOfBirth, and age. The dateOfBirth property is defined by
Exposing Properties 1
2 Exposing Properties
functions so it can include error checking. The age property is calculated, and is therefore defined as
read-only.
Note A CDATA section is required to make the script in the <script> element
opaque. For details, see Script Component Files and XML Conformance.
<public>
<property name="sname"/>
<property name="age">
<get internalName="readAge"/>
</property>
<property name="dateOfBirth">
<get internalName="readDOB"/>
<put internalName="writeDOB"/>
</property>
</public>
<script language="VBScript">
<![CDATA[
Dim sname ' Read-write sname property (no functions).
Dim gDOB ' Global variable used to store date of birth.
Function readDOB()
' Gets value of dateOfBirth property.
readDOB = gDOB
End Function
Function writeDOB(newDOB)
' Sets value of dateOfBirth property.
If isDate(gDOB) Then
'Error checking
gDOB = newDOB
End If
End Function
Function readAge()
' Calculates read-only age property.
If isDate(gDOB) Then
dobM = DatePart("m", gDOB)
dobD = DatePart("d", gDOB)
dobY = DatePart("yyyy", gDOB)
todayY = DatePart("yyyy", Date)
age = todayY - dobY
You can specify a default property for a script component so the host application can get or set the property's
value without explicitly naming the property. For example, if you have exposed a property called sname and
marked it as the default, you can work with it in either of these ways in Visual Basic:
2 Exposing Properties
Exposing Properties 3
To specify a default property, include an attribute assigning a special dispatch identifier (a dispid) to the
method. For more information about dispids, see Exposing Events.
• In the <property> element, include the attribute dispid="0", as in the following example:
Note This technique can be used to assign either a default property or a default
method, but not both. There can be only one element in the script component with the
dispid of zero.
See Also
Exposing Events | Exposing Methods | Script Component File Contents | Script Component Files and XML
Conformance
Exposing Properties 3
4 Exposing Properties
4 Exposing Properties
Exposing Events
To add event capability to a Windows® Script Component:
Some host environments also require that you generate a type library which they use to bind to events. For
details, see Creating a Script Component Type Library.
Note The Behavior handler exposes events in a slightly different way. For details, see
Exposing Custom Events in Behavior Script Components.
Declaring Events
Each event you want to be able to fire must be individually declared.
To declare an event
<public>
<property name="sname"/>
<method name="factorial"/>
<event name="namechanged"/>
<event name="querydone"/>
</public>
The process of creating a type library for script components automatically generates dispids for your script
component's events. However, if you prefer, you can specify your own dispids. Doing so allows you to:
• Guarantee that events in your script component will always have the same dispid. If the type library
generator assigns dispids, they can change each time the library is generated.
• Map events in your script component to dispids with specific numbers. For example, if you want to
fire a standard COM event such as an error notification, you can map your event to the values used by
convention in COM.
To specify a dispid for an event, include the dispid attribute in the <event> element, as in the following
example:
<public>
<event name="namechanged" dispid="22">
</public>
Dispids must be unique within the script component. You can specify a negative value for a dispid to map to
conventional events, but must use only specified ranges, such as -999 to -500 for controls. For details about
Exposing Events 1
2 Exposing Events
reserved dispid ranges, refer to documentation for DISPID in the MSDN library.
Note The dispid number zero is used to identify a default method or property. For more
details, see Exposing Methods and Exposing Properties.
Firing an Event
You can fire an event by calling the fireEvent method, specifying the name of the event to fire. You cannot
fire events that you did not expose in the <implements> element. You can fire an event in any script in your
script component file. For example, the following illustrates how you can fire an event when a property value
changes.
<script language="VBScript">
<![CDATA[
Sub put_lowercaseName(newLCName)
name = newLCName
fireEvent("namechanged")
End Sub
]]>
</script>
See Also
Exposing Custom Events in Behavior Script Components | Exposing Methods | Exposing Properties |
Handling Script Component Events in the Host Application | Script Component File Contents
2 Exposing Events
Creating a Script Component Type Library
You can generate a type library for your Windows® Script Component containing information about its
interfaces and members. In some host applications (such as Visual Basic), type libraries are necessary to
enable events for the script component, while in other host applications, type libraries are optional. However,
even if a type library is not required, generating one can make working with a script component easier and
less error-prone in the host application.
For example, if you are using Visual Basic as your host application, use the References dialog box to select a
script component's type library. This allows you to bind events to the script component and make them visible
in Visual Basic. In addition, when you are writing Visual Basic code that references the script component,
Visual Basic uses the type library information in statement completion and in the Object Browser so you can
easily see and use properties, methods, and events that the script component exposes.
Note For information about using a type library in the host application, refer to the
application's documentation.
• In Windows Explorer, right-click the script component .wsc file, and then choose Generate Type
Library.
A .tlb file is generated for the script component with the same name as the script component file,
written to the folder where the .wsc file is, and registered in the Windows registry.
For more precise control over generating type libraries, you can generate the type library dynamically from
script inside the script component file, or you can use a command-line interface.
1. In script inside the script component file, create an instance of the Component.GenerateTypeLib
object by using syntax such as the following:
{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
Name (Property) The internal name for the type library. This name is
displayed in some applications, such as the Visual Basic Object
Browser.
MajorVersion (Property) An integer value you assign.
MinorVersion (Property) An integer value you assign.
3. Call the type library object's Write method to create the .tlb file, then register it.
4. If you want to create an additional type library, call the GenerateTypeLib object's Reset method to
clear the list of script component files in the AddURL property, reset the URLs and any other
properties you want, and then call the Write method again.
For example, the following script in a <registration> element creates a type library dynamically.
Note A CDATA section is required to make the script in the <script> element opaque. For
details, see Script Component Files and XML Conformance.
<registration
description="My Test Component"
progid="Component.TestScript"
version="1"
classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}">
<script language="VBScript">
<![CDATA[
Function Register()
Set oTL = CreateObject("Scriptlet.GenerateTypeLib")
oTL.AddURL "d:\components\MyComponent.wsc" ' Script component URL.
oTL.AddURL "d:\components\YourComponent.wsc"
oTL.Path = "d:\components\MyComponent.tlb" ' .tlb path.
oTL.Doc = "Sample component typelib" ' Documentation string.
oTL.GUID = "{a1e1e3e0-a252-11d1-9fa1-00a0c90fffc0}"
oTL.Name = "MyComponentTLib" ' Internal name for tlb.
oTL.MajorVersion = 1
oTL.MinorVersion = 0
oTL.Write ' Write tlib to disk.
oTL.Reset ' Clear list of URLs in AddURL/.
End Function
]]>
</script>
</registration>
Command-line Interface
If you are comfortable using the Command Prompt window, you can call the Rundll32.exe program to
create type libraries.
For example, the following command creates a type library called MyComponent.tlb from the script
component MyComponent.wsc (the command is wrapped for clarity):
rundll32.exe c:\winnt\system32\scrobj.dll,GenerateTypeLib
-name:MyComponentTLib -file:d:\components\MyComponent.tlb
-doc:\"Sample component typelib\"
-guid:{a1e1e3e0-a252-11d1-9fa1-00a0c90fffc0} -major:1 -minor:0
-URL:d:\components\MyComponent.wsc
• If a property is defined by functions, the get and put functions must have the same number of
arguments with the same names. For details, see Exposing Properties.
Note It is possible to define a script component in which the get and put property
functions have different numbers of arguments, but you cannot create a type library
for that script component.
• If you are exposing events, you cannot use the same dispatch identifiers (dispid) more than once in a
script component. Additionally, you cannot use a negative value for the dispid unless it is within a
specified range. For details, see Exposing Methods.
• The ID attributes of elements in the script component must be unique. If you are generating a type
library from more than one script component, then the IDs must be unique in the type library as a
whole.
See Also
Script Component File Contents | Creating Registration Information | Checking For Errors in Script
Component Files | Script Component Files and XML Conformance
• In script Create instances of other objects directly in your script. For example, you can use the
CreateObject function in Microsoft® Visual Basic® Scripting Edition (VBScript) or the new
ActiveXObject Object in JScript.
• Using an OBJECT element Use an <object> element similar to the <OBJECT> tag you use in
HTML pages. Using an <object> element makes objects globally available to any script and allows
scripting tools to provide statement completion. It also provides a convenient way to summarize and
document the objects you use in your script component.
• Create an <object> element. This element should be inside the <component> element, but outside of
any other element such as a <script> element.
• Include a <reference> element in your script component that specifies the location and name of the
type library to include. For example:
<reference object="ADODB.Connection.2.0"/>
Referencing Resources
Resource elements can include information that might change between versions, strings that might be
To reference resources
1. In the script component, but outside of the <public> and <script> elements (and <implements>
element, if any), create one <resource> element for each resource you want to define, giving each
element a unique ID. The following example shows two <resource> elements:
Note A CDATA section is required to make the contents of the <resource> element
opaque to the parser. For details, see Script Component Files and XML
Conformance.
<component id="MyScriptlet">
<public>
<method name="random" internalName="getRandomNumber"/>
</public>
<resource id="errNonNumeric"><![CDATA[Non-numeric value passed]]>
</resource>
<resource id="errOutOfRange"><![CDATA[Passed value is out of range ]]>
</resource>
2. In your script, include the resource text or number by calling the getResourcefunction, as shown in the
following example.
Note A CDATA section is required to make the script in the <script> element
opaque to the parser. For details, see Script Component Files and XML
Conformance.
<script language="VBScript">
<![CDATA[
Function getRandomNumber(upperBound)
If IsNumeric(upperBound) Then
getRandomNumber = Cint(upperBound * Rnd + 1)
Else
getRandomNumber=getResource("errNonNumeric")
End If
End Function
]]>
</script>
See Also
Script Component File Contents | Referencing Another Script Component in the Same Package
For example, you might create one script component that implements the Automation interface and exposes a
series of properties and methods. A second script component in the same package might implement the ASP
interface, which provides access to the server object model for Microsoft® Internet Information Services
(IIS). You can then create a method or property in the Automation script component that exposes the ASP
script component and makes its members available.
To reference one script component from another, create a skeleton member a property or method in one
method that exposes the second script component.
For example, the following shows two script components in the same package. In the first script
component, the math method simply references the second script component, which exposes the add
method and the multiply method.
Note A CDATA section is required to make the script in the <script> element
opaque. For details, see Script Component Files and XML Conformance.
<?XML version="1.0"?>
<package>
<component id="component1">
<registration progid="Component.FrontEnd"/>
<public>
<property name="math"/>
</public>
<script language="JScript">
<![CDATA[
var math = createComponent("component2")
]]>
</script>
</component>
<component id="component2">
<registration progid="Component.Math"/>
<public>
<method name="add"/>
<method name="multiply"/>
</public>
<script language="JScript">
<![CDATA[
function add(n1, n2){
return n1+n2;
}
function multiply(n1, n2){
return n1*n2;
}
]]>
</script>
</component>
</package>
' Creates a second object that references the math method directly.
Set o2 = o1.math()
msgbox(o2.add(4,5))
msgbox(o2.multiply(4,5))
Each time you call the createComponent() function, it creates a new instance of the referenced script
component. If you need to preserve instance information between calls, store the pointer to the second script
component in a global variable, as in the following example.
Note A CDATA section is required to make the script in the <script> element opaque. For
details, see Script Component Files and XML Conformance.
<component id="component1">
<registration progid="Component.FrontEnd"/>
<public>
<property name="math">
<get/>
</property>
</public>
<script language="JScript">
<![CDATA[
var m = createComponent("component2")
function get_math(){
return m
}
]]>
</script>
</component>
See Also
• Check for XML validity. For details, see Script Component Files and XML Conformance.
• Allow notification for syntax and run-time errors. By default, if an error occurs in a script component
file, a generic error message is displayed. By specifying error notification, you can have the script
component parser display details about the error.
• Allow debugging. By default, you cannot use the script debugger for script components. If you enable
debugging, you can launch the script debugger in response to an error, by setting a breakpoint, or with
a Stop (Microsoft® Visual Basic® Scripting Edition (VBScript)) or debugger (JScript) statement.
• Include the <?component?> processing instruction at the top of the script component file (but after the
optional <?XML ?> declaration) with one or more of the following attributes:
• error Set this to true to display detailed error messages for syntax or run-time errors in the
script component.
• debug Set this to true to enable debugging. If this debugging is not enabled, you cannot
launch the script debugger for a script component in any way.
For example, the following enables all three error reporting options:
Tip Turn error reporting off before deploying your script component to a production
environment.
See Also
Script Component File Contents | Using The Script Component Wizard | Creating Registration Information |
Creating a Script Component Type Library | Script Component Files and XML Conformance
Note Script components written for DHTML Behaviors are instantiated differently than
traditional COM objects. For details, see Using DHTML Behaviors on the Microsoft Site
Builder Network (SBN) Web site.
There are a variety of options for creating an instance of the script component, depending on the host
application, the type of script component you are using, and where the script component is deployed. The
primary difference, however, is whether you want to create an instance of the script component locally (on the
same computer as the application) or remotely (on another computer).
In either case, there are a few points to bear in mind. If you create an instance of the script component and
change the .wsc file while using that instance, your instance of the component is not updated. To update it,
create a new instance of the script component.
The exact properties and methods you can use are defined by the <public> element and by scripts in the script
component file. If you are working in an environment that supports statement completion, such as Visual
Basic, you can see a script component's properties and methods if you generate and use a type library. For
details, see Creating a Script Component Type Library.
If your attempt to create an instance of the script component fails, a likely cause is a syntax or run-time error
in the script component file. A parsing error in any XML element (including the <registration> element) can
cause the instantiation to fail. While you are developing your script component file, set error checking options
in the <?component?> processing instruction as described in Checking For Errors in Script Component Files.
Tip To make it easier for the host application to know about the COM interfaces exposed by
a script component, the script component run-time can generate a type library, which contains
information about the properties, methods, and events available in the script component. For
details, see Creating a Script Component Type Library.
Note If your host application is Visual Basic and you want to handle events fired by the
script component, you must bind the object early with a Dim statement that includes the
WithEvents keyword, such as the following:
Dim WithEvents scMyComponent As MyComponent
Private Sub Command1_Click()
Set scMyComponent=CreateObject("MyComponent")
End Sub
Note For details, see Handling Script Component Events in the Host Application. This is not
necessary if you do not intend to write handlers for script component events.
On a Web page, you can use the <OBJECT> tag to create an instance of the script component. You must
know the class ID of the script component and include it in the <OBJECT> tag, as in the following example:
<OBJECT
ID="oComponent"
CLASSID="clsid:855c8606-49ba-11d2-a428-00c04f8ec80b">
</OBJECT>
If the script component is not registered on the local computer, you can use the script component moniker to
create an instance of it. The moniker is supported in functions such as GetObject. The script component
run-time, Scrobj.dll, must be registered on the local computer.
Note The GetObject function is not supported for script components in Microsoft® Internet
Explorer for security reasons.
For example, the following illustrates how to call the Visual Basic GetObject function to create an instance of
an unregistered script component:
If the .wsc file referenced by the moniker contains more than one script component, you can specify the script
component to instantiate by adding its name to the file name with a hash mark (#) as a delimiter. The
following creates an instance of the script component whose ID is "math" contained in the file
MyComponent.wsc:
Using a URL moniker allows you to create an instance of a script component that resides on another
computer, such as a Web server. Use a complete URL (with HTTP protocol) as the location for the script
component, as in the following example:
Internet Explorer 5.0 supports DHTML Behavior syntax for creating instances of script components, which
works somewhat differently than the traditional syntax for instantiating objects and will ensure that the script
component cannot access potential unsafe system objects. For an example, see Using DHTML Behaviors on
the Microsoft Site Builder Network (SBN) Web site.
Both computers must have basic DCOM installed. A computer is correctly configured with DCOM if it is
running any of the following:
• Windows NT 4.0
• Windows 95 running Internet Explorer 4.0
• Windows 95 with the OEM Service Release 2 (OSR2) or later. For details, see the Windows 95 OSR2
page on the Microsoft® Web site.
• Windows 95 with DCOM for Windows 95, version 1.2. For details, see the DCOM for Windows 95
page on the Microsoft® Web site.
• On the local computer, you do not require either the script component itself (.wsc file) or the script
component run-time (Scrobj.dll) at the time you instantiate the script component. However, you must
have a reference to the remote script component in the local Windows registry for DCOM. For details,
see Registering a Script Component.
• On the remote computer, you require the script component and the script component runtime. Both
must be registered.
When you create an instance of a remote script component, it works within your application as if it were a
local object; you call its methods and get and set its properties normally. However, the remote script
component's script runs on the remote machine and has access to that machine's resources (within any
limitations imposed by security, and so forth). Communication between the host application on the local
machine and the script component on the remote machine is handled automatically and invisibly by DCOM.
To create a remote instance of a script component, call the CreateObject method, passing it the name of the
remote computer as a parameter.
Note The ability to use CreateObject for instantiating remote script components requires
Visual Basic 6.0 or later or VBScript 5.0 or later.
The following Visual Basic example shows how to do this on a computer named "myserver":
Note There can be a slight delay when you first instantiate a remote script component while
DCOM establishes communication between the computers.
See Also
Creating Registration Information | Creating Script Components | How Script Components Work | Introducing
Script Components | Registering a Script Component
Note If you are creating a Behavior script component, events are exposed using the DHTML
object model. For details, see Exposing Custom Events in Behavior Script Components.
In Visual Basic, for example, you must use early (compile-time) binding to the component in order to receive
events. Early binding requires a type library, so you must have generated a type library for the script
component. For details, see Creating a Script Component Type Library. In addition, when you declare the
object variable for the component, you must specify the WithEvents keyword. (The class name used in the
Dim statement is the ID that you assigned in the script component's <component> element.)
See Also
Exposing Events
• <attach>elements to bind events from the containing document to functions created in a separate
<script> element in the script component.
• <layout>elements to define HTML text to be inserted into the containing document.
• <event>elements to define custom events that will be fired by the script component.
Behavior script components can also include custom properties and methods that extend those already
available for the element in the containing document. For details, see Exposing Properties and Methods in
Behavior Script Components.
The following example shows a Behavior script component that changes the color of an element in the
containing page whenever the mouse is passed over the element. To do this, the sample binds the DHTML
onmouseover and onmouseout events to functions in the script component that set the element's DHTML style
attribute. The sample also sets the document's link color when the document is initialized by binding to the
DHTML window object's onload event.
In addition to binding events to script, the script component also inserts text into any <H1> elements in the
containing document that are linked to this script component. Finally, it exposes and fires an event called
onchange, which extends the DHTML window object's event object with a custom property called newvalue.
Note A CDATA section is required to make the script in the <script> element opaque. For
details, see Script Component Files and XML Conformance.
<?XML version="1.0"?>
<component>
<implements type="Behavior">
<comment>The following will cause the do_nmousedown and
do_mouseout functions to be called when the mouse is
passed over the element in the containing document.</comment>
<comment> This will call the init function when the onload
event of window is fired.</comment>
<layout>
<h1>This is the HTML to show in the element</h1>
</layout>
<public>
<event name="onchange"/>
</public>
</implements>
<script language="JScript">
<![CDATA[
var normalColor, normalSpacing;
function do_onmouseover(){
// Save original values.
normalColor = style.color;
normalSpacing= style.letterSpacing;
style.color = "red";
style.letterSpacing = 2;
oEvent = createEventObject();
oEvent.newcolor = "red";
fireEvent("onchange",oEvent);
}
function do_onmouseout(){
// Reset to original values.
style.color = normalColor;
style.letterSpacing = normalSpacing;
}
function docinit(){
document.linkColor = "red";
}
]]>
</script>
</component>
• From a script component procedure, the implied this pointer in an event handler refers to the
containing function, not to the element on which the event is being fired.
• Just as in an HTML page, it is possible to place inline script within a <script> in a script component.
In this instance, the global variables normalColor and normalSpacing are defined in inline script.
Note Inline script is executed even before the behavior is applied to the element,
which limits what statements can be executed in inline script. For example, if the
same behavior in the example exposed a property called hiliteColor, the inline script
could refer to hiliteColor directly (in other words, it resolves against the script
component's namespace). It is illegal, however, to refer to hiliteColor as
Behavior.element.hiliteColor from an inline script, because at that point, the behavior
has not yet been applied to the element. For more information, see Scope Rules and
Timing Considerations later in this topic.
The following code from a hypothetical calculator script component demonstrates keyboard and mouse events
bound to a script component function called doCalc. The doCalc function uses the event object to get
information about the conditions under which the event was fired.
Note A CDATA section is required to make the script in the <script> element opaque. For
details, see Script Component Files and XML Conformance.
<implements type="Behavior">
<attach event="onclick" handler="doCalc"/>
<attach event="onkeydown" handler="doCalc"/>
</implements>
<script language="jscript">
<![CDATA[
function doCalc(oEventParam){
oElement = oEventParam.srcElement;
if(oEventParam.type == "keydown"){
sVal = KeyCodeToChar(oEventParam.keyCode);
}
else{
if (oEventParam.srcElement.type != "button"){
return;}
sVal = stripBlanks(oEventParam.srcElement.value);
}
}
// other script here
]]>
</script>
Scope Rules
When working with script components, you actually work with three namespaces: the behavior, the element,
and the containing document. Scope rules define the order in which name conflicts are resolved in a behavior
script component. A name will be resolved in this order:
The name is resolved to one defined by the behavior anywhere in the script component, whether a variable, a
behavior-defined property, a method, or an event.
If the name is not resolved successfully, it is resolved to a property, method, or event that applies to the
element.
Finally, the name is resolved to the name of a property, method, or event that applies to the window object in
the containing page.
In the following example, note how the names have been resolved, using the scope rules defined above:
• normalColor Resolves to the variable defined by the behavior at the top of the script.
• style Resolves to the style property of the element in the containing document.
<implements type="Behavior">
<attach event="onmouseover" handler="do_onmouseover"/>
<attach event="onmouseout "handler="do_onmouseout"/>
</implements>
<script language="JScript">
<![CDATA[
var normalColor, normalSpacing;
function event_onmouseover()
{
// Save original values.
normalColor = style.color;
normalSpacing = style.letterSpacing;
style.color = "red";
style.letterSpacing = 2;
}
function event_onmouseout()
{
// Reset to original values.
style.color = normalColor;
style.letterSpacing = normalSpacing;
}
]]>
</script>
Timing Considerations
When creating behaviors, it is important to know when the behavior is applied to the element. Until the
behavior has been applied, scripts cannot have access to the values of behavior-defined properties that might
be set in the document.
Because the behavior is encapsulated in a separate file from the HTML document, it is downloaded separately
from the rest of the document. As the document and behavior are parsed and loaded, the behavior receives
notifications of progress through the function specified with the attachNotification method. Currently, the
behavior is notified with a "contentChange" or a "documentReady" notification. The "contentChange"
notification is sent when the content of the element to which the behavior has been attached has been parsed,
and any time thereafter that the content of the element is changed. The "documentReady" notification is sent
when the document has been downloaded and parsed.
Because inline script in the script component file is executed as soon as the behavior is instantiated, the values
of behavior-defined attributes and properties that are being set in the document may not be accessible from an
inline script. However, these properties will be available as soon as the first "contentChange" notification is
sent.
See Also
Exposing Properties and Methods in Behavior Script Components | Exposing Custom Events in Behavior
Script Components | Behavior Handler Reference
A behavior can override an element's default behavior by exposing a property or method of the same name as
that which is already defined for the element.
Properties and methods are defined in a <public> element separate from the <implements> element used to
specify the Behavior handler. For details, see Exposing Properties and Exposing Methods.
Exposing a Property
Properties are exposed in a <public> element, as in any script component. The following script component
fragment shows a Behavior script component that exposes the custom property hiliteColor. If the containing
page does not specifically set the property's value, the default is set to "red."
Note A CDATA section is required to make the script in the <script> element opaque. For
details, see Script Component Files and XML Conformance.
<public>
<property name="hiliteColor"/>
</public>
<implements type="Behavior">
<attach for="window" event="onload" handler="event_onload">
</implements>
<script language="JScript">
<![CDATA[
var hiliteColor;
function event_onload(){
// Initialize the properties.
if (hiliteColor == null){
hiliteColor = "red";}
}
// Further script here.
]]>
</script>
Exposing a Method
Exposing a method in a Behavior script component is identical to doing so in an Automation script
component. For details, see Exposing Methods. In a Behavior script component, methods exposed in the script
component extend those already available for the element in the containing document.
See Also
<public>
<event name="onResultChange" />
</public>
The event can then be fired by calling the fireEvent method in script:
<script language="JScript">
// Other code here.
fireEvent("onResultChange");
// Other code here.
</script>
A behavior can override an element's default behavior by exposing an event of the same name as one that is
already defined for the element. For example, a behavior that exposes an onclick event can override the
element's default onclick event.
• Change existing event object properties, such as keyCode, that have been set by in the calling event.
• Create new (expando) properties of the event object in order to pass information about your event
back to the containing event.
In your script component code, call the createEventObject method to create a new instance of an event object,
and then set one or more properties on the new event object. When you call the fireEvent method, you can
pass the new event object with the event name.
To create a new expando property, simply name it when assigning its value in your script. The following
shows how you can create a new property called myprop for the event object:
oEvent = createEventObject();
oEvent.myprop = "a new value"
Note You can create expando properties only if you are using Microsoft® JScript® (or
JavaScript). This feature is not supported in Microsoft® Visual Basic® Scripting Edition
(VBScript).
Example
The following script component fragment is derived from a calculator script component sample. The sample
defines a custom onResultChange event that is fired to the containing document whenever the result changes.
Event-specific information (the actual calculation result) is passed via the expando property called result.
Note A CDATA section is required to make the script in the <script> element opaque. For
details, see Script Component Files and XML Conformance.
<implements type="Behavior">
<attach event="onclick" handler="doCalc"/>
</implements>
<script language="JScript">
<![CDATA[
function doCalc()
{
// Code here to perform calculation. Results are placed into
// the variable sResult.
oEvent = createEventObject();
oEvent.result = sResult;
fireEvent("onResultChange",oEvent);
}
]]>
</script>
The following shows what the containing page looks like. When the onResultChange event fires, the results of
the calculation are extracted from expando property result of the DHTML window.event object and displayed
in the resultWindow <DIV> element.
<HTML>
<HEAD>
<xml:namespace prefix="LK" />
<style>
LK\:CALC {behavior:url(calc.wsc)}
</style>
<script language="JScript">
function showResults(){
resultWindow.innerText=window.event.result;
}
</script>
</HEAD>
See Also
Values
COMHandlerName
The name of the interface handler to reference. Interface handlers are usually implemented as DLLs,
which you must be sure are available and registered in the production environment for your script
component. Some handlers, such as the Automation and ASP handlers, are built into the script
component run-time (Scrobj.dll). Examples of available interface handlers include:
Interface handler Description How implemented
ASP Allows a script component to Built into Scrobj.dll
get access to the Microsoft
Internet Information Services
(IIS) Active Server Pages
(ASP) object model.
DHTML Behaviors Allows a behavior script Built into Scrobj.dll
component to communicate
with the containing page so it
can fire events and access the
DHTML object model.
internalName
(Optional) A name you can use to reference the handler in your script. By default, properties,
methods, events, and other members of a script component are available in the global namespace.
However, if there is a naming conflict between <implements> elements, the names can be
disambiguated by prefixing them with the ID of the <implements> element to which they belong, as
in the following:
[...]
<script language="JScript">
// [...]
sctBehavior.fireEvent("onResultChange",oEvent);
</script>
fAssumed
(Optional) A Boolean flag indicating that the internalName is assumed in scripts. The default value
for this attribute is true, and members of the object model exposed by the handler are added to the
global script namespace and can be accessed unqualified. You only need to include this attribute if
you want to set it to false and therefore hide members of a specific <implements> element.
Remarks
Interface handlers extend the script component run-time. An interface handler is a compiled component
(generally written in C++) that implements specific COM interfaces.
Script components by default implement the COM Automation interface (specifically, the IDispatchEx COM
<implements> Element 1
2 <implements> Element
interface). The Automation object's properties, methods, and events are defined in the script component's
<public> element. Because the Automation handler is implemented by default, you do not need to implement
it with the <implements> element.
Script components can also implement additional COM interfaces by including an <implements> element.
Inside the <implements> element, you specify information specific to the interfaces you are implementing.
Each interface handler requires different information. For example, a Behavior script component can include
<attach> and <layout> elements that are specific to the DHTML Behavior interface.
Example
<implements type="Behavior">
<event name="onResultChange" />
</implements>
See Also
2 <implements> Element
<property> Element
Declares a property.
or
<property name="propertyName">
<get [internalName="getFunctionName"] />
<put [internalName="putFunctionName"] />
</property>
Values
propertyName
The name of the property to expose. Unless you specify an internalName attribute, this name must
match the name of a global variable that will be used to hold the property's value.
propertyVariable
(Optional) The name of the global variable in the scriptlet file's <script> element that will hold the
value for propertyName. If you do not include the internalName attribute, the property value is
maintained in a variable named the same as propertyName. Specifying the internalName attribute
allows you to use different names for the property and its corresponding global variable.
getFunctionName
(Optional) The name of a procedure that is used to read the value of the property. If you include <get>
element but no <put> element, the property will be read-only. If you include a <get> element but do
not specify an internalName attribute, the method used to read the property value must have the name
of the property plus the get_ prefix (for example, get_lastname).
putFunctionName
(Optional) The name of a procedure that is used to write the value of the property. If you include a
<put> element but no <get> element, the property will be write-only. If you include a <put> element
but do not specify an internalName attribute, the method used to read the property value must have
the name of the property plus the put_ prefix (for example, put_lastname).
Tip In XML, you can implement elements that have no content (such as the
<property> element) by closing the element with />.
Remarks
Properties can be exposed as simple values. In that case, the property is treated as a global variable inside the
script component file.
You can also implement properties as procedures (functions or subroutines), which allows you to calculate a
property value and to control whether a property is read-only, read-write, or write-only. In this technique,
properties are implemented as a procedure (function or subroutine) in a separate <script> element. The
<property> element maps the name of the property to the procedures used to implement it. The names of the
procedures must match the internal names you specified in the <property> element.
When putFunctionName is called, it is passed one argument that contains the value to which to set the
property.
In addition to the standard syntax shown above, you can use a shorthand notation to specify information what
would otherwise be added using child tags. For example, if you want to declare a property with a "get" and
"put" accessor of the same name as the property, you can use the following syntax:
<property> Element 1
2 <property> Element
<property name="myproperty" get put/>
<property name="myproperty">
<get/>
<put/>
</property>
If you wanted to explicitly name those accessors differently from the default, you can use the following
syntax:
To specify a default property, include the attribute dispid="0" in the <property> element. For details, see
Exposing Properties.
Example
The following script component fragment shows the definition for four properties (sname, age, dateOfBirth,
and mstatus). The sname property is a simple value. The age property is read-only, and is implemented with
the function readAge. The dateOfBirth property is read-write, and is implemented wih the functions readDOB
and writeDOB. Finally, the mstatus property is implemented with the default functions get_mstatus and
put_mstatus.
Note A CDATA section is required to make the script in the <script> element opaque. For
details, see Script Component Files and XML Conformance.
<public>
<property name="sname"/>
<property name="age">
<get internalName="readAge"/>
</property>
<property name="dateOfBirth">
<get internalName="readDOB"/>
<put internalName="writeDOB"/>
</property>
<property name="mstatus">
<get/>
<put/>
</property>
</public>
<script language="VBScript">
<![CDATA[
Dim sname ' Read-write sname property (no functions).
Dim gDOB ' Global variable used to store date of birth.
Dim gMStatus ' global variable used to store marital status.
Function readDOB()
' Gets value of dateOfBirth property.
readDOB = gDOB
End Function
Function writeDOB(newDOB)
' Sets value of dateOfBirth property.
If isDate(gDOB) Then
' Error checking.
gDOB = newDOB
End If
End Function
2 <property> Element
<property> Element 3
Function readAge()
' Calculates read-only age property.
If isDate(gDOB) Then
dobM = DatePart("m", gDOB)
dobD = DatePart("d", gDOB)
dobY = DatePart("yyyy", gDOB)
todayY = DatePart("yyyy", Date)
age = todayY - dobY
Function get_mstatus()
' Reads value of mstatus property.
get_mstatus = gMStatus
End Function
Function put_mstatus(s)
' Writes value of mstatus property.
If s = "M" Or s = "S" Then
gMStatus = s
Else
gMStatus = "?"
End If
End Function
]]>
</script>
See Also
<event> Element | <method> Element | Exposing Events | Exposing Methods | Exposing Properties
<property> Element 3
4 <property> Element
4 <property> Element
<public> Element
Encloses the script component's property, method, and event declarations.
<public>
<property name="pname"/>
<method name="mname"/>
<event name="ename"/>
</public>
See Also
<event> Element | <method> Element | <property> Element | Exposing Events | Exposing Methods | Exposing
Properties
<public> Element 1
2 <public> Element
2 <public> Element
<reference> Element
Includes a reference to an external type library.
Values
progID
The program ID from which the type library can be derived, which can include a version number (for
example, ADO.Recordset.2.0). This can include the explicit program ID of a type library, or the
program ID of the executable (such as a .DLL) that incorporates the type library. If you use the object
attribute, you do not need to specify a version attribute, because the version can be inferred from the
program ID.
If the object attribute is specified, you cannot also specify a guid attribute.
typelibGUID
The GUID of the type library to reference. If the guid attribute is specified, you cannot also specify an
object attribute.
version
(Optional) The version number of the type library to use. It must be in the form <major
version>[.<minor version>]. If a version is not specified, the default version is 1.0. If the object
attribute is used to specify the type library and the version is not specified, the version is derived from
the Registry key for the specified program ID. If none can be found, the default is 1.0.
Remarks
Referencing a type library in your script component allows you to use constants defined in the type library in
scripts. The <reference> element looks up and makes available the type library associated with a specific
program ID or type library name. Type library information can be available in .tlb, .olb, or .dll files.
The <reference> element should appear inside the <component> element. If there is more than one script
component in the package, the type library applies to only the script component in whose <component>
element it is declared.
Example
In the following script component fragment, referencing the type library for ADO (contained in the file
MSAD015.DLL) allows you to use ADO constants such as adStateOpen in your scripts.
Note A CDATA section is required to make the script in the <script> element opaque. For
details, see Script Component Files and XML Conformance.
<reference object="ADODB.Connection.2.0"/>
<registration progid="ADOScriptlet"/>
<public>
<property name="cnnstate"/>
<method name="openConnection"/>
<method name="closeConnection"/>
</public>
<script language="VBScript">
<![CDATA[
Dim cnn
Dim cnnState
Function openConnection()
Set cnn = CreateObject("ADODB.Connection")
<reference> Element 1
2 <reference> Element
cnn.ConnectionString =
"driver={SQL Server};server=myserver;uid=sa;database=pubs"
cnn.Open
If cnn.State = adStateOpen Then
cnnState = "open"
Else
cnnState = "closed"
End If
End Function
Function closeConnection()
cnn.Close
cnnState = "closed"
End Function
]]>
</script>
See Also
2 <reference> Element
<registration> Element
Defines information used to register the script component as a COM component.
or
Values
progID
(Optional) A text name that programmers use to reference your script component when creating an
instance of it. For example, if your script component's program ID is Component.MyComponent, you
can create an instance of it in Microsoft® Visual Basic using a statement such as the following:
Note Although a progid attribute is optional, you must include either a progid or a
classid attribute (you can include both). If only the progid attribute is specified, the
class ID is generated automatically. If only the class ID is created, then no progid is
registered and the object can be created only by referencing the class ID directly.
GUID
(Optional) A GUID that you have generated using a class ID generation program (such as
Uuidgen.exe). If you do not include a class ID, the registration program assigns a class ID to your
script component.
description
(Optional) A text description of the script component that is stored in the registry and that is used in
certain tools such as the Visual Basic object browser.
version
(Optional) A numeric version number that you assign. The version is appended to the program ID
with a period (for example, MyComponent.1) when applications request a version-specific name. Use
only numbers (decimal points are not allowed).
Note The registration attributes can appear in any order in the <registration>
element.
remoteFlag
(Optional) A Boolean value indicating whether the script component can be instantiated remotely
using DCOM. For details, see Creating Remote Instances of Script Components in the topic "Using a
Script Component in an Application."
Remarks
After a script component is created, it can be registered using a program such as Regsvr32.exe, which reads
the information in the <registration> element and writes it into the computer's Windows Registry. For
example, a script component can be registered this way:
regsvr32 file:\\myserver\MyComponent.wsc
<registration> Element 1
2 <registration> Element
Note A <registration> element is not required in all cases. For example, a script component
that implements the DHTML Behaviors interface handler in Microsoft® Internet Explorer 5.0
does not need to be registered, because Internet Explorer registers the behaviors as they are
detected on the page. For details about registration requirements, see the documentation for
the interface handler you are implementing and note also which host the script component
will be used in.
If you do not include class ID information, the registration program assigns a class ID to your script
component at the time it is registered. However, the script component will have a different class ID
everywhere it is registered. It is highly recommended that you provide a class ID for the script component
yourself, to ensure that your script component has the same class ID on all computers on which it is
registered.
Allowing the registration program to create a class ID can cause problems if you use the script component
with development tools that store class IDs. If the registration creates a new class ID each time, it will not
match the the ID stored by the application.
You can optionally run scripts when a script component is registered and unregistered. To do so, include a
<script> element within the <registration> element. To run script during registration, write a register( )
function. To run script when the script component has been unregistered, include an unregister( ) function.
Example
The following shows a typical <registration> element that includes both a prog ID and a class ID.
<registration
progid="Component.TestScript"
classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"
description="My Test Component"
version="1"/>
The following registration element allows the script component to be instantiated via DCOM:
<registration>
progid="Component.TestScript"
classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"
version="1"
description="My Test Component"
remotable=true/>
The following example shows a <registration> element that includes script to be run when the script
component is registered and unregistered.
Note A CDATA section is required to make the script in the <script> element opaque. For
details, see Script Component Files and XML Conformance.
<registration
progid="Component.TestScript"
classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}">
version="1"
description="My Test Component">
<script language="VBScript">
Function register()
MsgBox "Component 'My Test Component' registered."
End Function
Function unregister()
MsgBox "Component 'My Test Component' unregistered."
End Function
2 <registration> Element
<registration> Element 3
</script>
]]>
</registration>
See Also
<registration> Element 3
4 <registration> Element
4 <registration> Element
<resource> Element
Isolates textual or numeric data that should not be hard-coded into the script component's scripts.
<resource id="resourceID">
text or number here
</resource>
Values
ResourceID
A unique identifier for the resource within the script component.
Remarks
The <resource> element allows you to isolate strings or numbers in your script component that you want to
intermingle with script in your script component. For example, resource elements are typically used to
maintain strings that might be localized into another language.
To get the value of a resource, call the getResource function, passing it the ID of the resource you want to use.
Example
The following script component fragment defines a resource (called errNonNumeric) and demonstrates how
to use it in script.
Note A CDATA section is required to make the script in the <script> element opaque. For
details, see Script Component Files and XML Conformance.
<public>
<method name="random" internalName="getRandomNumber"/>
</public>
<resource id="errNonNumeric">
Non-numeric value passed
</resource>
<script language="VBScript">
<![CDATA[
Function getRandomNumber(upperBound)
If IsNumeric(upperBound) Then
getRandomNumber = Cint(upperBound * Rnd + 1)
Else
getRandomNumber=getResource("errNonNumeric")
End If
End Function
]]>
</script>
See Also
<resource> Element 1
2 <resource> Element
2 <resource> Element
<script> Element
Defines the script component's behavior.
<script language="language">
script here
</script>
Values
language
The name of the scripting language used in the script component file, such as Microsoft® Visual
Basic® Scripting Edition (VBScript) or JScript.
Remarks
If XML validation is not enabled, the XML parser ignores all lines inside the <script> element. However, if
XML validation is enabled by including the <?XML ?> declaration at the top of the script component file, the
XML parser can misinterpret greater than (<), less than (>), and other symbols used in script as XML
delimiters.
If you are creating a file that conforms closely to XML syntax, you must make sure that characters in your
script element are not treated as XML reserved characters. To do so, enclose the actual script in a
<![CDATA[ ... ]]> section. For details about XML validation, see Script Component Files and XML
Conformance.
Note Do not include a CDATA section unless you also include the <?XML ?> declaration.
Example
<?XML version="1.0"?>
<component id="ScriptletFactorial">
<registration progid="Component.Factorial"/>
<public>
<method name="factorial"/>
</public>
<script language="VBScript">
<![CDATA[
Function factorial(n)
If isNumeric(n) Then
If n <= 1 Then
factorial = 1
Else
factorial = n * factorial(n-1)
End If
Else
factorial = -2 ' Error code.
End If
End Function
]]>
</script>
</component>
See Also
<script> Element 1
2 <script> Element
2 <script> Element
<component> Element
Encloses an entire Windows Script Component definition.
<component id=componentid>
script component information here
</component>
Values
componentid
A string that uniquely identifies the script component. This value is useful if a document contains
multiple script components or when you are generating one type library for several script components.
Identifiers must begin with a letter and can contain no spaces. The identifier must be unique within a
script component package.
If specified, this value functions as the class name for the script component in the host application.
For example, if you specify the component ID "MyComponent" in the <component> element, the
script component is identified as the class MyComponent in the Visual Basic object browser. If no
component ID is specified, the default value is ComponentCoClass.
Remarks
In script component files, an entire script component definition including<registration>, <public> and
<implements> elements must appear inside a <component> element. If the file contains multiple script
components, they must in turn be enclosed within a <package> element.
Example
The following shows a simple but complete script component that includes a factorial method and a name
property.
Note A CDATA section is required to make the script in the <script> element opaque. For
details, see Script Component Files and XML Conformance.
<?XML version="1.0"?>
<component>
<registration>
description="My Test Component"
progid="Component.TestScript"
version="1"
classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"
</registration>
<public>
<property name="name"/>
<method name="factorial"/>
</public>
<script language="VBScript">
<![CDATA[
Function factorial(n)
If isNumeric(n) Then
If n <= 1 Then
factorial = 1
Else
factorial = n*factorial(n-1)
End If
Else
<component> Element 1
2 <component> Element
factorial = -2 ' Error code.
End If
End Function
]]>
</script>
</component>
See Also
2 <component> Element
<attach> Element
Binds an event from the containing document to a function in the script component.
Values
eventName
The event being bound, such as onmouseclick.
functionName
The name of the procedure (function or subroutine) in the script component file that is executed in
response to the event. If this attribute is omitted, it is generated.
If the for attribute is not specified, the default value of the handler attribute is the value of the event
attribute. If the for attribute is specified, the default handler attribute value is the string generated by
concatenating the for attribute value, "_", and the event attribute value.
elementName
The element associated with the event, used for containing elements to which DHTML Behaviors are
not explicitly attached. The only possible values for the for attribute are "document," "window," and
"element." If the for attribute is not included, "element" is the default and the event is assumed to be
fired on the element to which the behavior is attached.
Example
In the following example, the <attach> element binds three events to functions. For example, the DHTML
onmouseover element is bound to the script component's do_onmouseover function. The functions bound to
the DHTML onmouseover and onmouseout events are executed only if they are fired on the element in the
containing document to which the behavior is attached. The docinit function is explicitly bound to the
DHTML document object's onload event.
Note A CDATA section is required to make the script in the <script> element opaque. For
details, see Script Component Files and XML Conformance.
<?XML version="1.0"?>
<component id="bvrscript component1">
<registration progID="Behaviorscript component"/>
<implements type="Behavior">
<attach event="onmouseover" handler="do_onmouseover"/>
<attach event="onmouseout "handler="do_onmouseout"/>
<attach for="window" event="onload" handler="docinit"/>
</implements>
<script language="JScript">
<![CDATA[
var normalColor, normalSpacing;
function do_onmouseover(){
// Save original values.
normalColor = style.color;
normalSpacing= style.letterSpacing;
style.color = "red";
style.letterSpacing = 2;
}
function do_onmouseout(){
// Reset to original values.
style.color = normalColor;
style.letterSpacing = normalSpacing;
}
function docinit(){
document.linkColor = "red";
<attach> Element 1
2 <attach> Element
}
]]>
</script>
</component>
See Also
2 <attach> Element
element Property
Returns the element to which the behavior is being applied.
[oElement = ] Behavior.element
Values
oElement
Element to which the behavior is being applied.
Behavior
The ID of the <implements> element used to implement the Behavior interface.
Note By default, the properties and methods exposed by the Behavior handler are
automatically added to the global script namespace and can be accessed without
referencing the Behavior handler ID. In this case, instead of using Behavior.element
as shown in the syntax, the property can be used in script simply as element. For
more details, see the <implements> element.
Remarks
With this property, a behavior is able to communicate with the containing document. All properties, methods,
and events exposed by the DHTML object model are accessible through this property.
Example
The following script component fragment implements an expanding and collapsing table of contents using a
script component. The script component attaches to the element's DHTML onmouseover event. It sets the
DHTML cursor property of the element to "hand" to signal the user that the element can be clicked in order
to toggle visibility of its children.
Note A CDATA section is required to make the script in the <script> element opaque. For
details, seeScript Component Files and XML Conformance.
<public>
<attach event="onmouseover" handler="event_onmouseover");
</public>
<implements type="Behavior"/>
<script language="JScript">
<![CDATA[
function event_onmouseover()
{
oElement = window.event.srcElement;
if (oElement == element)
oElement.style.cursor = "hand";
}
]]>
</script>
See Also
For general information about applying behaviors to DHTML elements, see the "Using DHTML Behaviors"
topic on the Site Builder Network (SBN)
element Property 1
2 element Property
2 element Property
<layout> Element
Defines HTML text inserted into the containing document.
<layout>
<HTMLtag>Inserted text</HTMLtag>
</layout>
Values
HTMLTag
The name of HTML tag for which the element's text is a replacement.
Remarks
When the behavior is called, the text in the <layout> element is read into the corresponding element in the
containing document. This behavior is equivalent to setting the element's DHTML innerHTML property.
If the script component is not defined to be XML-conformant, the contents of the <layout> element are
opaque. However, if the script component is XML-conformant, the contents of the <layout> element must
explicitly be made opaque by including them in a CDATA. For more details, see Script Component Files and
XML Conformance.
Example
The following shows an example of a script component with a <layout> element. Because the script
component contains the <?XML ?> declaration at the top, the <layout> element contains a CDATA section to
make the contents of the <layout> element opaque to the XML parser.
See Also
For general information about applying behaviors to DHTML elements, see the "Using DHTML Behaviors"
topic on the Site Builder Network (SBN).
<layout> Element 1
2 <layout> Element
Microsoft® Windows® Script Interfaces introduce a new way for an application to add
scripting and OLE Automation capabilities. With the advent of the interfaces, hosts can call
upon disparate scripting engines from multiple sources and vendors to perform scripting
between components. The implementation of the script itselflanguage, syntax, persistent
format, execution model, and so onis left to the script vendor. The designers have taken care
to allow hosts that rely on Windows Script to use arbitrary language back ends.
This list contains definitions of the scripting-related terms used in this document.
Term Definition
Named An OLE COM object (preferably one that supports OLE Automation) that
item the host deems interesting to the script. Examples include the HTML Page
and Browser in a Web browser, and the Document and Dialogs in
Microsoft Word.
Script The data that makes up the program that the scripting engine runs. A script
can be any contiguous executable data, including pieces of text, blocks of
pcode, or even machine-specific executable byte codes. A host loads a
script into the scripting engine through one of the IPersist* interfaces or
through the IActiveScriptParse interface.
Scripting The OLE object that processes scripts. A scripting engine implements the
engine IActiveScript and, optionally, IActiveScriptParse interfaces.
Scripting The application or program that owns the Windows Script engine. The host
host implements the IActiveScriptSite and, optionally, IActiveScriptSiteWindow
interfaces.
Script The language in which a script is written (VBScript, for example) and the
language semantics of that language.
Windows Script components fall into two categories: Windows Script hosts and Windows
Script engines. A host creates a scripting engine and calls on the engine to run the scripts.
Examples of Windows Script hosts include:
2 <layout> Element
<layout> Element 3
♦ Lisp
To make implementation of the host as flexible as possible, an OLE Automation wrapper for
Windows Script is provided. However, a host that uses this wrapper object to instantiate the
scripting engine does not have the degree of control over the run-time name space, the
persistence model, and so on, that it would if it used Windows Script directly.
The Windows Script design isolates the interface elements required only in an authoring
environment so that nonauthoring hosts (such as browsers and viewers) and script engines
(for example, VBScript) can be kept lightweight.
The following illustration shows the interaction between an Windows Script host and an
Windows Script engine.
Following is a description of the steps involved in the interaction between the host and
engine. The actual nesting of the function calls is omitted for clarity.
1. Create a Project. The host loads a project or document. (This step is not particular to
Windows Script, but is included here for completeness.)
2. Create the Windows Script Engine. The host calls CoCreateInstance to create a new
Windows Script engine, specifying the class identifier (CLSID) of the specific scripting engine
to use. For example, the HTML browsing component of Internet Explorer receives the scripting
engine's class identifier through the CLSID= attribute of the HTML <OBJECT> tag.
3. Load the Script. If the script contents have been persisted, the host calls the script engine's
IPersist*::Load method to feed it the script storage, stream, or property bag. Otherwise, the
host uses either the IPersist*::InitNew or IActiveScriptParse::InitNew method to create a null
script. A host that maintains a script as text can use IActiveScriptParse::ParseScriptText to
feed the scripting engine the text of the script, after calling IActiveScriptParse::InitNew.
4. Add Named Items. For each top-level named item (such as pages and forms) imported into
the scripting engine's name space, the host calls the IActiveScript::AddNamedItem method to
create an entry in the engine's name space. This step is not necessary if top-level named items
are already part of the persistent state of the script loaded in step 3. A host does not use
IActiveScript::AddNamedItem to add sublevel named items (such as controls on an HTML
page); rather, the engine indirectly obtains sublevel items from top-level items by using the
host's ITypeInfo and IDispatch interfaces.
5. Run the Script. The host causes the engine to start running the script by setting the
SCRIPTSTATE_CONNECTED flag in the IActiveScript::SetScriptState method. This call would
likely perform any scripting engine construction work, including static binding, hooking up to
events (see below), and executing code, in a way similar to a scripted main() function.
6. Get Item Information. Each time the script engine needs to associate a symbol with a
top-level item, it calls the IActiveScriptSite::GetItemInfo method, which returns information
<layout> Element 3
4 <layout> Element
about the given item.
7. Hook Up Event Advise. Before starting the actual script, the scripting engine connects to the
events of all the relevant objects through the IConnectionPoint interface.
8. Invoke Properties and Methods. As the script runs, the scripting engine realizes references
to methods and properties on named objects through IDispatch::Invoke or other standard
OLE binding mechanisms.
When implementing Microsoft® Windows® Script host, you can safely assume that a
scripting engine will only call the IActiveScriptSite interface in the context of the base thread
as long as the host does the following:
♦ Chooses a base thread (generally the thread that contains the message loop).
♦ Instantiates the scripting engine in the base thread.
♦ Calls scripting engine methods only from the base thread, except where specifically allowed,
as in the cases of IActiveScript::InterruptScriptThread and IActiveScript::Clone.
♦ Calls the scripting engine's dispatch object only from the base thread.
♦ Ensures that the message loop runs in the base thread if a window handle is provided.
♦ Ensures that objects in the host's object model only source events in the base thread.
These rules are automatically followed by all single-threaded hosts. The restricted model
described above is intentionally loose enough to allow a host to abort a stuck script by calling
IActiveScript::InterruptScriptThread from another thread (initiated by a CTRL+BREAK handler
or the like), or to duplicate a script in a new thread using IActiveScript::Clone.
Also, none of these restrictions apply to a host that chooses to implement a free-threaded
IActiveScriptSite interface and a free-threaded object model. Such a host can use the
IActiveScript interface from any thread, without restriction.
To implement an Microsoft® Windows® Script engine, create an OLE COM object that
supports the following interfaces.
Interface Description
IActiveScriptParse Provides the ability to add script text, evaluate expressions, and so
on. Implementation of this interface is optional; however, if it is not
implemented, the script engine must implement one of the
IPersist* interfaces in order to load a script.
4 <layout> Element
<layout> Element 5
Note: It is possible that the scripting engine will never be called upon to save or restore a
script state through IPersist*. Instead, IActiveScriptParse is used by calling
IActiveScriptParse::InitNew to create a blank script, then scriptlets are added and connected
to events with IActiveScriptParse::AddScriptlet and general code is added with
IActiveScriptParse::ParseScriptText. Nonetheless, a scripting engine should fully implement
at least one IPersist* interface (preferably IPersistStreamInit), because other host
applications may try to make use of them.
The following sections describe implementing a Windows Scripting engine in more detail.
♦ Registry Standard
♦ Script Engine States
♦ Scripting Engine Threading
Registry Standard
Category Decription
At any given time, an Windows Script engine can be in one of several states.
State Descriptioon
<layout> Element 5
6 <layout> Element
6 <layout> Element
<layout> Element 7
<layout> Element 7
8 <layout> Element
The following illustration shows the actions that the scripting engine
performs during the various state transitions.
8 <layout> Element
<layout> Element 9
marshaling. (Unfortunately, this also means that the scripting engine must be
implemented as an in-process server, because OLE does not currently support
interprocess marshaling of free-threaded objects.) Synchronization is the
responsibility of the scripting engine. For scripting engines that are not
internally reentrant, or for language models that are not multithreaded,
synchronization could be as simple as serializing access to the scripting
engine with a mutex. Of course certain methods, such as
IActiveScript::InterruptScriptThread, should not be serialized in this way so
that a stuck script can be terminated from another thread.
◊ The script site is always called in the context of a host thread. That is, the
scripting engine never calls the script site in the context of a thread that the
scripting engine created, but only from within a scripting engine method that
was called from the host through IActiveScript and its derivatives, through
the exposed scripting engine's dispatch object, through a Windows message,
or from an event source in the host's object model.
◊ The script site is never called from within the context of a simple thread state
control method (for example, the IActiveScript::InterruptScriptThread
method) or from the IActiveScript::Clone method.
♦ IActiveScriptSite
♦ IActiveScriptSiteWindow
The following interfaces are specific to Windows Script Engines.
♦ IActiveScript
♦ IActiveScriptError
♦ IActiveScriptParse
The following enumerations are specific to Windows Script Engines.
♦ SCRIPTSTATE
♦ SCRIPTTHREADSTATE
The IActiveScript interface provides the methods necessary to initialize the scripting engine.
The scripting engine must implement the IActiveScript interface.
Method Description
<layout> Element 9
10 <layout> Element
AddTypeLib Adds a type library to the name space for the script.
HRESULT AddNamedItem(
LPCOLESTR pstrName, // address of item name
DWORD dwFlags // item flags
);
Adds the name of a root-level item to the scripting engine's name space. A root-level item is an object with
properties and methods, an event source, or all three.
S_OK Success.
E_UNEXPECTED The call was not expected (for example, the scripting engine has not yet been loaded
or initialized).
pstrName
[in] Address of a buffer that contains the name of the item as viewed from the script. The name must
be unique and persistable.
dwFlags
[in] Flags associated with an item. Can be a combination of these values:
10 <layout> Element
<layout> Element 11
Value Meaning
SCRIPTITEM_CODEONLY Indicates that the named item represents a code-only object, and
that the host has no IUnknown to be associated with this
code-only object. The host only has a name for this object. In
object-oriented languages such as C++, this flag would create a
class. Not all languages support this flag.
SCRIPTITEM_ISPERSISTENT Indicates that the item should be saved if the scripting engine is
saved. Similarly, setting this flag indicates that a transition back
to the initialized state should retain the item's name and type
information (the scripting engine must, however, release all
pointers to interfaces on the actual object).
SCRIPTITEM_ISSOURCE Indicates that the item sources events that the script can sink.
Child objects (properties of the object that are in themselves
objects) can also source events to the script. This is not recursive,
but it provides a convenient mechanism for the common case, for
example, of creating a container and all of its member controls.
SCRIPTITEM_ISVISIBLE Indicates that the item's name is available in the name space of
the script, allowing access to the properties, methods, and events
of the item. By convention the properties of the item include the
item's children; therefore, all child object properties and methods
(and their children, recursively) will be accessible.
SCRIPTITEM_NOCODE Indicates that the item is simply a name being added to the
script's name space, and should not be treated as an item for
which code should be associated. For example, without this flag
being set, VBScript will create a separate module for the named
item, and C++ might create a separate wrapper class for the
named item.
HRESULT AddTypeLib(
REFGUID guidTypeLib, // CLSID of type library
DWORD dwMaj, // major version number
DWORD dwMin, // minor version number
DWORD dwFlags // option flags
);
Adds a type library to the name space for the script. This is similar to the #include directive in C/C++. It
allows a set of predefined items such as class definitions, typedefs, and named constants to be added to the
run-time environment available to the script.
<layout> Element 11
12 <layout> Element
S_OK Success.
E_UNEXPECTED The call was not expected (for example, the scripting engine has not
yet been loaded or initialized).
guidTypeLib
[in] CLSID of the type library to add.
dwMaj
[in] Major version number.
dwMin
[in] Minor version number.
dwFlags
[in] Option flags. Can be the following:
Value Meaning
SCRIPTTYPELIB_ISCONTROL The type library describes an ActiveX control used by the host.
HRESULT Clone(
IActiveScript **ppscript // receives pointer to IActiveScript
);
Clones the current scripting engine (minus any current execution state), returning a loaded scripting engine
that has no site in the current thread. The properties of this new scripting engine will be identical to the
properties the original scripting engine would be in if it were transitioned back to the initialized state.
S_OK Success.
E_UNEXPECTED The call was not expected (for example, the scripting engine has not yet been loaded
or initialized).
ppscript
[out] Address of a variable that receives a pointer to the IActiveScript interface of the cloned scripting
engine. The host must create a site and call the IActiveScript::SetScriptSite method on the new
scripting engine before it will be in the initialized state and, therefore, usable.
12 <layout> Element
<layout> Element 13
This method is used for multithreaded server hosts that can run multiple instances of the same script. The
scripting engine may return E_NOTIMPL, in which case the host can achieve the same result by duplicating
the persistent state and creating a new instance of the scripting engine with an IPersist* interface.
This method can be called from non-base threads without resulting in a non-base callout to host objects or to
the IActiveScriptSite interface.
HRESULT Close(void);
Causes the scripting engine to abandon any currently loaded script, lose its state, and release any interface
pointers it has to other objects, thus entering a closed state. Event sinks, immediately executed script text, and
macro invocations that are already in progress are completed before the state changes (use
IActiveScript::InterruptScriptThread to cancel a running script thread). This method must be called by the
creating host before the interface is released to prevent circular reference problems.
S_OK Success.
E_UNEXPECTED The call was not expected (for example, the scripting engine was already in
the closed state).
OLESCRIPT_S_PENDING The method was queued successfully, but the state hasn't changed yet.
When the state changes, the site will be called back on the
IActiveScriptSite::OnStateChange method.
S_FALSE The method succeeded, but the script was already closed.
HRESULT GetCurrentScriptThreadID(
SCRIPTTHREADID *pstidThread // receives scripting thread identifier
);
Retrieves a scripting-engine-defined identifier for the currently executing thread. The identifier can be used in
subsequent calls to script thread execution-control methods such as the IActiveScript::InterruptScriptThread
method.
pstidThread
[out] Address of a variable that receives the script thread identifier associated with the current thread.
The interpretation of this identifier is left to the scripting engine, but it can be just a copy of the
Windows thread identifier. If the Win32 thread terminates, this identifier becomes unassigned and can
subsequently be assigned to another thread.
This method can be called from non-base threads without resulting in a non-base callout to host objects or to
the IActiveScriptSite interface.
<layout> Element 13
14 <layout> Element
Next
IActiveScript::GetScriptDispatch
HRESULT GetScriptDispatch(
LPCOLESTR pstrItemName // address of item name
IDispatch **ppdisp // receives IDispatch pointer
);
Retrieves the IDispatch interface for the methods and properties associated with the currently running script.
S_OK Success.
E_UNEXPECTED The call was not expected (for example, the scripting engine has not yet been loaded
or initialized).
S_FALSE The scripting engine does not support a dispatch object; the ppdisp parameter is set
to NULL.
pstrItemName
[in] Address of a buffer that contains the name of the item for which the caller needs the associated
dispatch object. If this parameter is NULL, the dispatch object contains as its members all of the
global methods and properties defined by the script. Through the IDispatch interface and the
associated ITypeInfo interface, the host can invoke script methods or view and modify script
variables.
ppdisp
[out] Address of a variable that receives a pointer to the object associated with the script's global
methods and properties. If the scripting engine does not support such an object, NULL is returned.
Because methods and properties can be added by calling the IActiveScriptParse interface, the IDispatch
interface returned by this method can dynamically support new methods and properties. Similarly, the
IDispatch::GetTypeInfo method should return a new, unique ITypeInfo interface when methods and
properties are added. Note, however, that language engines must not change the IDispatch interface in a way
that is incompatible with any previous ITypeInfo interface returned. That implies, for example, that DISPIDs
will never be reused.
HRESULT GetScriptSite(
REFIID iid, // interface identifier
void **ppvSiteObject // address of host site interface
);
Retrieves the site object associated with the Windows Script engine.
S_OK Success.
14 <layout> Element
<layout> Element 15
S_FALSE No site has been set; the ppvSiteObject parameter is set to NULL.
iid
[in] Identifier of the requested interface.
ppvSiteObject
[out] Address of the location that receives the interface pointer to the host's site object.
HRESULT GetScriptState(
SCRIPTSTATE *pss // address of structure for state information
);
Retrieves the current state of the scripting engine. This method can be called from non-base threads without
resulting in a non-base callout to host objects or to the IActiveScriptSite interface.
pss
[out] Address of a variable that receives a value defined in the SCRIPTSTATE enumeration. The
value indicates the current state of the scripting engine associated with the calling thread.
HRESULT GetScriptThreadID(
DWORD dwWin32ThreadID, // Win32 thread identifier
SCRIPTTHREADID *pstidThread // receives scripting thread identifier
);
Retrieves a scripting-engine-defined identifier for the thread associated with the given Win32 thread.
S_OK Success.
E_UNEXPECTED The call was not expected (for example, the scripting engine has not yet been loaded
or initialized) and therefore failed.
dwWin32ThreadID
[in] Thread identifier of a running Win32 thread in the current process. Use the
GetCurrentScriptThreadID function to retrieve the thread identifier of the currently executing thread.
pstidThread
[out] Address of a variable that receives the script thread identifier associated with the given Win32
thread. The interpretation of this identifier is left to the scripting engine, but it can be just a copy of
the Windows thread identifier. Note that if the Win32 thread terminates, this identifier becomes
<layout> Element 15
16 <layout> Element
The retrieved identifier can be used in subsequent calls to script thread execution control methods such as the
IActiveScript::InterruptScriptThread method.
This method can be called from non-base threads without resulting in a non-base callout to host objects or to
the IActiveScriptSite interface.
HRESULT GetScriptThreadState(
SCRIPTTHREADID stidThread, // identifier of script thread
SCRIPTTHREADSTATE *pstsState // receives state flag
);
S_OK Success.
E_UNEXPECTED The call was not expected (for example, the scripting engine has not yet been loaded
or initialized).
stidThread
[in] Identifier of the thread for which the state is desired, or one of the following special thread
identifiers:
Value Meaning
SCRIPTTHREADID_BASE The base thread; that is, the thread in which the scripting engine was
instantiated.
This method can be called from non-base threads without resulting in a non-base callout to host objects or to
the IActiveScriptSite interface.
HRESULT InterruptScriptThread(
SCRIPTTHREADID stidThread, // identifier of thread
const EXCEPINFO *pexcepinfo, // receives error information
DWORD dwFlags
);
16 <layout> Element
<layout> Element 17
Interrupts the execution of a running script thread (an event sink, an immediate execution, or a macro
invocation). This method can be used to terminate a script that is stuck (in an infinite loop, for example). It
can be called from non-base threads without resulting in a non-base callout to host objects or to the
IActiveScriptSite method.
S_OK Success.
E_UNEXPECTED The call was not expected (for example, the scripting engine has not yet been loaded
or initialized).
stidThread
[in] Identifier of the thread to interrupt, or one of the following special thread identifier values:
Value Meaning
SCRIPTTHREADID_BASE The base thread; that is, the thread in which the
scripting engine was instantiated.
Value Meaning
HRESULT SetScriptSite(
IActiveScriptSite *pScriptSite // address of host script site
);
Informs the scripting engine of the IActiveScriptSite interface site provided by the host. This method must be
called before any other IActiveScript interface methods can be used.
<layout> Element 17
18 <layout> Element
S_OK Success.
E_FAIL An unspecified error occurred; the scripting engine was unable to finish initializing
the site.
E_UNEXPECTED The call was not expected (for example, a site was already set).
pScriptSite
[in] Address of the host-supplied script site to be associated with this instance of the scripting engine.
The site must be uniquely assigned to this scripting engine instance; it cannot be shared with other
scripting engines.
HRESULT SetScriptState(
SCRIPTSTATE ss // identifier of new state
);
Puts the scripting engine into the given state. This method can be called from non-base threads without
resulting in a non-base callout to host objects or to the IActiveScriptSite interface.
S_OK Success.
E_FAIL The scripting engine does not support the transition back to the initialized
state. The host must discard this scripting engine and create, initialize, and
load a new scripting engine to achieve the same effect.
E_UNEXPECTED The call was not expected (for example, the scripting engine has not yet
been loaded or initialized) and therefore failed.
OLESCRIPT_S_PENDING The method was queued successfully, but the state has not changed yet.
When the state changes, the site will be called back through the
IActiveScriptSite::OnStateChange method.
S_FALSE The method succeeded, but the script was already in the given state.
ss
[in] Sets the scripting engine to the given state. Can be one of the values defined in the
SCRIPTSTATE enumeration.
For more information about scripting engine states, see Script Engine States.
18 <layout> Element
<layout> Element 19
Method Description
GetSourcePosition Retrieves the location in the source code where an error occurred.
GetSourceLineText Retrieves the line in the source file where an error occurred.
HRESULT GetExceptionInfo(
EXCEPINFO *pexcepinfo // structure for exception information
);
Retrieves information about an error that occurred while the scripting engine was running a script.
pexcepinfo
[out] Address of an EXCEPINFO structure that receives error information.
HRESULT GetSourceLineText(
BSTR *pbstrSourceLine // address of buffer for source line
);
Retrieves the line in the source file where an error occurred while a scripting engine was running a script.
• Returns S_OK if successful, or E_FAIL if the line in the source file was not retrieved.
pbstrSourceLine
[out] Address of a buffer that receives the line of source code in which the error occurred.
HRESULT GetSourcePosition(
DWORD *pdwSourceContext, // context cookie
ULONG *pulLineNumber, // line number of error
LONG *pichCharPosition // character position of error
);
Retrieves the location in the source code where an error occurred while the scripting engine was running a
script.
<layout> Element 19
20 <layout> Element
pdwSourceContext
[out] Address of a variable that receives a cookie that identifies the context. The interpretation of this
parameter depends on the host application.
pulLineNumber
[out] Address of a variable that receives the line number in the source file where the error occurred.
pichCharPosition
[out] Address of a variable that receives the character position in the line where the error occurred.
If the Windows Script engine allows raw text code scriptlets to be added to the script or
allows expression text to be evaluated at run time, it implements the IActiveScriptParse
interface. For interpreted scripting languages that have no independent authoring
environment, such as VBScript, this provides an alternate mechanism (other than IPersist*)
to get script code into the scripting engine, and to attach script fragments to various object
events.
Method Description
ParseScriptText Parses the given code scriptlet, adding declarations into the name
space and evaluating code as appropriate.
HRESULT AddScriptlet(
LPCOLESTR pstrDefaultName, // address of default name of scriptlet
LPCOLESTR pstrCode, // address of scriptlet text
LPCOLESTR pstrItemName, // address of item name
LPCOLESTR pstrSubItemName, // address of subitem name
LPCOLESTR pstrEventName, // address of event name
LPCOLESTR pstrDelimiter, // address of end-of-scriptlet delimiter
DWORD dwSourceContextCookie, // application-defined value for debugging
ULONG ulStartingLineNumber, // starting line of the script
DWORD dwFlags, // scriptlet flags
BSTR *pbstrName, // address of actual name of scriptlet
EXCEPINFO *pexcepinfo // address of exception information
);
Adds a code scriptlet to the script. This method is used in environments where the persistent state of the script
is intertwined with the host document and the host is responsible for restoring the script, rather than through
an IPersist* interface. The primary examples are HTML scripting languages that allow scriptlets of code
embedded in the HTML document to be attached to intrinsic events (for instance,
ONCLICK="button1.text='Exit'").
20 <layout> Element
<layout> Element 21
S_OK Success.
E_NOTIMPL This method is not supported; the scripting engine does not support
adding event-sinking scriptlets.
E_UNEXPECTED The call was not expected (for example, the scripting engine has not
yet been loaded or initialized) and therefore failed.
pstrDefaultName
[in] Address of a default name to associate with the scriptlet. If the scriptlet does not contain naming
information (as in the ONCLICK example above), this name will be used to identify the scriptlet. If
this parameter is NULL, the scripting engine manufactures a unique name, if necessary.
pstrCode
[in] Address of the scriptlet text to add. The interpretation of this string depends on the scripting
language.
pstrItemName
[in] Address of a buffer that contains the item name associated with this scriptlet. This parameter, in
addition to pstrSubItemName, identifies the object for which the scriptlet is an event handler.
pstrSubItemName
[in] Address of a buffer that contains the name of a subobject of the named item with which this
scriptlet is associated; this name must be found in the named item's type information. This parameter
is NULL if the scriptlet is to be associated with the named item instead of a subitem. This parameter,
in addition to pstrItemName, identifies the specific object for which the scriptlet is an event handler.
pstrEventName
[in] Address of a buffer that contains the name of the event for which the scriptlet is an event handler.
pstrDelimiter
[in] Address of the end-of-scriptlet delimiter. When the pstrCode parameter is parsed from a stream of
text, the host typically uses a delimiter, such as two single quotation marks ("), to detect the end of the
scriptlet. This parameter specifies the delimiter that the host used, allowing the scripting engine to
provide some conditional primitive preprocessing (for example, replacing a single quotation mark [']
with two single quotation marks for use as a delimiter). Exactly how (and if) the scripting engine
makes use of this information depends on the scripting engine. Set this parameter to NULL if the host
did not use a delimiter to mark the end of the scriptlet.
dwSourceContextCookie
[in] Application-defined value that is used for debugging purposes.
ulStartingLineNumber
[in] Zero-based value that specifies which line the parsing will begin at.
dwFlags
[in] Flags associated with the scriptlet. Can be a combination of the following values:
SCRIPTTEXT_ISVISIBLE Indicates that the script text should be visible (and, therefore,
callable by name) as a global method in the name space of the
script.
SCRIPTTEXT_ISPERSISTENT
<layout> Element 21
22 <layout> Element
Indicates that the code added during this call should be saved
if the scripting engine is saved (for example, through a call to
IPersist*::Save), or if the scripting engine is reset by way of
a transition back to the initialized state. For more information
about this state, see Script Engine States.
pbstrName
[out] Actual name used to identify the scriptlet. This will be, in order of preference: a name explicitly
specified in the scriptlet text, the default name provided in pstrDefaultName, or a unique name
synthesized by the scripting engine.
pexcepinfo
[out] Address of a structure containing exception information. This structure should be filled in if
DISP_E_EXCEPTION is returned.
HRESULT InitNew(void);
Before the scripting engine can be used, one of the following methods must be called: IPersist*::Load,
IPersist*::InitNew, or IActiveScriptParse::InitNew. The semantics of this method are identical to
IPersistStreamInit::InitNew, in that this method tells the scripting engine to initialize itself. Note that it is
not valid to call both IPersist*::InitNew or IActiveScriptParse::InitNew and IPersist*::Load, nor is it
valid to call IPersist*::InitNew, IActiveScriptParse::InitNew, or IPersist*::Load more than once.
HRESULT ParseScriptText(
LPCOLESTR pstrCode, // address of scriptlet text
LPCOLESTR pstrItemName, // address of item name
IUnknown *punkContext, // address of debugging context
LPCOLESTR pstrDelimiter, // address of end-of-scriptlet delimiter
DWORD dwSourceContextCookie, // application-defined value for debugging
ULONG ulStartingLineNumber, // starting line of the script
DWORD dwFlags, // scriptlet flags
VARIANT *pvarResult, // address of buffer for results
EXCEPINFO *pexcepinfo // address of buffer for error data
);
Parses the given code scriptlet, adding declarations into the name space and evaluating code as appropriate.
S_OK Success.
22 <layout> Element
<layout> Element 23
E_NOTIMPL This method is not supported. The scripting engine does not support
run-time evaluation of expressions or statements.
E_UNEXPECTED The call was not expected (for example, the scripting engine is in the
uninitialized or closed state, or the SCRIPTTEXT_ISEXPRESSION flag
was set and the scripting engine is in the initialized state).
pstrCode
[in] Address of the scriptlet text to evaluate. The interpretation of this string depends on the scripting
language.
pstrItemName
[in] Address of the item name that gives the context in which the scriptlet is to be evaluated. If this
parameter is NULL, the code is evaluated in the scripting engine's global context.
punkContext
[in] Address of the context object. This object is reserved for use in a debugging environment, where
such a context may be provided by the debugger to represent an active run-time context. If this
parameter is NULL, the engine uses pstrItemName to identify the context.
pstrDelimiter
[in] Address of the end-of-scriptlet delimiter. When pstrCode is parsed from a stream of text, the host
typically uses a delimiter, such as two single quotation marks ("), to detect the end of the scriptlet.
This parameter specifies the delimiter that the host used, allowing the scripting engine to provide
some conditional primitive preprocessing (for example, replacing a single quotation mark ['] with two
single quotation marks for use as a delimiter). Exactly how (and if) the scripting engine makes use of
this information depends on the scripting engine. Set this parameter to NULL if the host did not use a
delimiter to mark the end of the scriptlet.
dwSourceContextCookie
[in] Application-defined value that is used for debugging purposes.
ulStartingLineNumber
[in] Zero-based value that specifies which line the parsing will begin at.
dwFlags
[in] Flags associated with the scriptlet. Can be a combination of these values:
Value Meaning
SCRIPTTEXT_ISPERSISTENT Indicates that the code added during this call should be saved if the
scripting engine is saved (for example, through a call to
IPersist*::Save), or if the scripting engine is reset by way of a
transition back to the initialized state.
SCRIPTTEXT_ISVISIBLE Indicates that the script text should be visible (and, therefore, callable
by name) as a global method in the name space of the script.
pvarResult
[out] Address of a buffer that receives the results of scriptlet processing, or NULL if the caller expects
no result (that is, the SCRIPTTEXT_ISEXPRESSION value is not set).
pexcepinfo
[out] Address of a structure that receives exception information. This structure is filled if
IActiveScriptParse::ParseScriptText returns DISP_E_EXCEPTION.
<layout> Element 23
24 <layout> Element
If the scripting engine is in the initialized state, no code will actually be evaluated during this call; rather, such
code is queued and executed when the scripting engine is transitioned into (or through) the started state.
Because execution is not allowed in the initialized state, it is an error to call this method with the
SCRIPTTEXT_ISEXPRESSION flag when in the initialized state.
The scriptlet can be an expression, a list of statements, or anything allowed by the script language. For
example, this method is used in the evaluation of the HTML <SCRIPT> tag, which allows statements to be
executed as the HTML page is being constructed, rather than just compiling them into the script state.
The code passed to this method must be a valid, complete portion of code. For example, in VBScript it is
illegal to call this method once with Sub Function(x) and then a second time with End Sub. The parser must
not wait for the second call to complete the subroutine, but rather must generate a parse error because a
subroutine declaration was started but not completed.
For more information about script states, see Script Engine States.
The host must create a site for the Windows Script engine by implementing the
IActiveScriptSite interface. Usually, this site will be associated with the container of all the
objects that are visible to the script (for example, the ActiveX Controls). Typically, this
container will correspond to the document or page being viewed. Microsoft Internet Explorer,
for example, would create such a container for each HTML page being displayed. Each
ActiveX control (or other automation object) on the page, and the scripting engine itself,
would be enumerable within this container.
Method Description
GetLCID Retrieves the locale identifier that the host uses for displaying
user-interface elements.
OnStateChange Informs the host that the scripting engine has changed states.
OnScriptError Informs the host that an execution error occurred while the
engine was running the script.
OnEnterScript Informs the host that the scripting engine has begun executing
the script code.
OnLeaveScript Informs the host that the scripting engine has returned from
executing script code.
HRESULT GetDocVersionString(
BSTR *pbstrVersionString // address of document version string
);
24 <layout> Element
<layout> Element 25
Retrieves a host-defined string that uniquely identifies the current document version. If the related document
has changed outside the scope of Windows Script (as in the case of an HTML page being edited with
NotePad), the scripting engine can save this along with its persisted state, forcing a recompile the next time
the script is loaded.
pstrVersionString
[out] Address of the host-defined document version string.
If E_NOTIMPL is returned, the scripting engine should assume that the script is in sync with the document.
HRESULT IActiveScriptSite::GetItemInfo(
LPCOLESTR pstrName, // address of item name
DWORD dwReturnMask, // bit mask for information retrieval
IUnknown **ppunkItem, // address of pointer to item's IUnknown
ITypeInfo **ppTypeInfo // address of pointer to item's ITypeInfo
);
Allows the scripting engine to obtain information about an item added with the IActiveScript::AddNamedItem
method.
S_OK Success.
pstrName
[in] The name associated with the item, as specified in the IActiveScript::AddNamedItem method.
dwReturnMask
[in] A bit mask specifying what information about the item should be returned. The scripting engine
should request the minimum amount of information possible because some of the return parameters
(for example, ITypeInfo) can take considerable time to load or generate. Can be a combination of the
following values:
Value Meaning
<layout> Element 25
26 <layout> Element
ppTypeInfo
[out] Address of a variable that receives a pointer to the ITypeInfo interface associated with the item.
This parameter receives NULL if dwReturnMask does not include the SCRIPTINFO_ITYPEINFO
value, or if type information is not available for this item. If type information is not available, the
object cannot source events, and name binding must be realized with the
IDispatch::GetIDsOfNames method. Note that the ITypeInfo interface retrieved describes the item's
coclass (TKIND_COCLASS) because the object may support multiple interfaces and event interfaces.
If the item supports the IProvideMultipleTypeInfo interface, the ITypeInfo interface retrieved is the
same as the index zero ITypeInfo that would be obtained using the
IProvideMultipleTypeInfo::GetInfoOfIndex method.
This method retrieves only the information indicated by the dwReturnMask parameter; this improves
performance. For example, if an ITypeInfo interface is not needed for an item, it is simply not specified in
dwReturnMask.
HRESULT GetLCID(
LCID *plcid // address of variable for language identifier
);
Retrieves the locale identifier associated with the host's user interface. The scripting engine uses the identifier
to ensure that error strings and other user-interface elements generated by the engine appear in the appropriate
language.
S_OK Success.
plcid
[out] Address of a variable that receives the locale identifier for user-interface elements displayed by
the scripting engine.
If this method returns E_NOTIMPL, the system-defined locale identifier should be used.
HRESULT OnEnterScript(void);
Informs the host that the scripting engine has begun executing the script code.
The scripting engine must call this method on every entry or reentry into the scripting engine. For example, if
the script calls an object that then fires an event handled by the scripting engine, the scripting engine must call
IActiveScriptSite::OnEnterScript before executing the event, and must call the
IActiveScriptSite::OnLeaveScript method after executing the event but before returning to the object that fired
26 <layout> Element
<layout> Element 27
the event. Calls to this method can be nested. Every call to this method requires a corresponding call to
IActiveScriptSite::OnLeaveScript.
HRESULT IActiveScriptSite::OnLeaveScript(void);
Informs the host that the scripting engine has returned from executing script code.
The scripting engine must call this method before returning control to a calling application that entered the
scripting engine. For example, if the script calls an object that then fires an event handled by the scripting
engine, the scripting engine must call the IActiveScriptSite::OnEnterScript method before executing the event,
and must call IActiveScriptSite::OnLeaveScript after executing the event before returning to the object that
fired the event. Calls to this method can be nested. Every call to IActiveScriptSite::OnEnterScript requires
a corresponding call to this method.
HRESULT IActiveScriptSite::OnScriptError(
IActiveScriptError *pase // address of error interface
);
Informs the host that an execution error occurred while the engine was running the script.
• Returns S_OK if the error was correctly handled, or an OLE defined error code otherwise.
pase
[in] Address of the error object's IActiveScriptError interface. A host can use this interface to obtain
information about the execution error.
HRESULT OnScriptTerminate(
VARIANT *pvarResult, // address of script results
EXCEPINFO *pexcepinfo // address of structure with exception informat
);
pvarResult
[in] Address of a variable that contains the script result, or NULL if the script produced no result.
pexcepinfo
[in] Address of an EXCEPINFO structure that contains exception information generated when the
script terminated, or NULL if no exception was generated.
The scripting engine calls this method before the call to the IActiveScriptSite::OnStateChange method, with
the SCRIPTSTATE_INITIALIZED flag set, is completed. This method can be used to return completion
<layout> Element 27
28 <layout> Element
status and results to the host. Note that many script languages, which are based on sinking events from the
host, have life spans that are defined by the host. In this case, this method may never be called.
HRESULT IActiveScriptSite::OnStateChange(
SCRIPTSTATE ssScriptState // new state of engine
);
Informs the host that the scripting engine has changed states.
ssScriptState
[in] Value that indicates the new script state. See the IActiveScript::GetScriptState method for a
description of the states.
This interface is implemented by hosts that support a user interface on the same object as
IActiveScriptSite. Hosts that do not support a user interface, such as servers, would not
implement the IActiveScriptSiteWindow interface. The scripting engine accesses this
interface by calling QueryInterface from IActiveScriptSite.
Method Description
GetWindow Retrieves the window handle that can act as the owner of a
pop-up window that the scripting engine must display.
EnableModeless Causes the host to enable or disable its main window as well
as any modeless dialog boxes.
HRESULT IActiveScriptSite::EnableModeless(
BOOL fEnable // enable flag
);
Causes the host to enable or disable its main window as well as any modeless dialog boxes.
fEnable
[in] Flag that, if TRUE, enables the main window and modeless dialogs or, if FALSE, disables them.
28 <layout> Element
<layout> Element 29
Microsoft® Windows® Script Interfaces Language Reference
Previous
IActiveScriptSiteWindow::GetWindow Next
HRESULT GetWindow(
HWND *phwnd // address of variable for window handle
);
Retrieves the handle to a window that can act as the owner of a pop-up window that the scripting engine must
display.
phwnd
[out] Address of a variable that receives the window handle.
♦ SCRIPTSTATE
♦ SCRIPTTHREADSTATE
Contains named constant values that specify the state of a scripting engine. This enumeration is used by the
IActiveScript::GetScriptState, IActiveScript::SetScriptState, and IActiveScriptSite::OnStateChange methods.
SCRIPTSTATE_UNINITIALIZED
Script has just been created, but has not yet been initialized using an IPersist* interface and
IActiveScript::SetScriptSite.
SCRIPTSTATE_INITIALIZED
Script has been initialized, but is not running (connecting to other objects or sinking events) or
executing any code. Code can be queried for execution by calling the
IActiveScriptParse::ParseScriptText method.
SCRIPTSTATE_STARTED
Script can execute code, but is not yet sinking the events of objects added by the
IActiveScript::AddNamedItem method.
SCRIPTSTATE_CONNECTED
Script is loaded and connected for sinking events.
SCRIPTSTATE_DISCONNECTED
Script is loaded and has a run-time execution state, but is temporarily disconnected from sinking
events.
<layout> Element 29
30 <layout> Element
SCRIPTSTATE_CLOSED
Script has been closed. The scripting engine no longer works and returns errors for most methods.
30 <layout> Element