510
What Is JScript?

What is JScript?

  • Upload
    xarmana

  • View
    312

  • Download
    1

Embed Size (px)

Citation preview

Page 1: What is JScript?

What Is JScript?

Page 2: What is JScript?
Page 3: What is JScript?

Table of ContentsWhat Is JScript?.................................................................................................................................................1

Using JScript............................................................................................................................................1

Writing JScript Code..........................................................................................................................................1Statements................................................................................................................................................1Comments................................................................................................................................................1Assignments and Equality.......................................................................................................................2Expressions..............................................................................................................................................2

JScript Variables.................................................................................................................................................1Declaring Variables.................................................................................................................................1Naming Variables....................................................................................................................................1Coercion...................................................................................................................................................2

JScript Data Types..............................................................................................................................................1String Data Type......................................................................................................................................1Number Data Type...................................................................................................................................1

Integer Values....................................................................................................................................1Floating-point Values........................................................................................................................2

Boolean Data Type..................................................................................................................................2Null Data Type.........................................................................................................................................3Undefined Data Type...............................................................................................................................3

JScript Operators................................................................................................................................................1Computational Operators.........................................................................................................................1

Logical Operators..............................................................................................................................1

Controlling Program Flow.................................................................................................................................1Using Conditional Statements.................................................................................................................1Conditional Operator...............................................................................................................................2Using Loops.............................................................................................................................................2Using for Loops.......................................................................................................................................3Using for...in Loops.................................................................................................................................3Using while Loops...................................................................................................................................4Using break and continue Statements......................................................................................................4

JScript Objects....................................................................................................................................................1Objects as Arrays.....................................................................................................................................1

JScript Reserved Words.....................................................................................................................................1Future Reserved Words............................................................................................................................1

Advanced Object Creation.................................................................................................................................1Writing Constructors................................................................................................................................1Using Prototypes to Create Objects.........................................................................................................1

Recursion.............................................................................................................................................................1

Variable Scope.....................................................................................................................................................1

What Is JScript?

i

Page 4: What is JScript?

Table of ContentsCopying, Passing, and Comparing Data...........................................................................................................1

By Value vs. By Reference......................................................................................................................1Passing Parameters to Functions..............................................................................................................1Testing Data.............................................................................................................................................2

Special Characters..............................................................................................................................................1

Troubleshooting Your Scripts...........................................................................................................................1Syntax Errors...........................................................................................................................................1Order of Script Interpretation...................................................................................................................1Automatic Type Coercion........................................................................................................................1Operator Precedence................................................................................................................................1Using for...in Loops with Objects............................................................................................................1with Keyword...........................................................................................................................................2this Keyword............................................................................................................................................2Writing a Script That Writes a Script in Internet Explorer......................................................................2Implicit Window References in Internet Explorer...................................................................................2

Microsoft JScript Features - ECMA.................................................................................................................1

Microsoft JScript Features - Non-ECMA.........................................................................................................1

abs Method..........................................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

acos Method.........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

anchor Method....................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

asin Method.........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

atan Method.........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

atan2 Method.......................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

big Method...........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

What Is JScript?

ii

Page 5: What is JScript?

Table of Contentsblink Method.......................................................................................................................................................1

Remarks...................................................................................................................................................1Requirements.....................................................................................................................................1

bold Method.........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

ceil Method..........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

charAt Method....................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

compile Method...................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

concat Method (Array).......................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

concat Method (String).......................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

cos Method...........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

dimensions Method.............................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................2

escape Method.....................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

eval Method.........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

exec Method.........................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

exp Method..........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

What Is JScript?

iii

Page 6: What is JScript?

Table of Contentsfixed Method........................................................................................................................................................1

The required strVariable reference is any String object or literal............................................................1Remarks.............................................................................................................................................1

floor Method........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

fontcolor Method.................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

fontsize Method...................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

getDate Method...................................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

getDay Method....................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

getHours Method................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

getMinutes Method.............................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

getMonth Method................................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

getSeconds Method.............................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

getTime Method..................................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

getTimezoneOffset Method................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

getVarDate Method............................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

What Is JScript?

iv

Page 7: What is JScript?

Table of ContentsgetYear Method...................................................................................................................................................1

Remarks...................................................................................................................................................1Example.............................................................................................................................................1

indexOf Method..................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

italics Method......................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

item Method.........................................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

join Method..........................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

lastIndexOf Method............................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

lbound Method....................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

link Method..........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

log Method...........................................................................................................................................................1Return Value............................................................................................................................................1

Requirements.....................................................................................................................................1

match Method......................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

max Method.........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

min Method..........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

parse Method.......................................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

What Is JScript?

v

Page 8: What is JScript?

Table of ContentsparseFloat Method..............................................................................................................................................1

Remarks...................................................................................................................................................1Requirements.....................................................................................................................................1

parseInt Method..................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

pow Method.........................................................................................................................................................1Arguments................................................................................................................................................1

Example.............................................................................................................................................1

random Method...................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

replace Method....................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

reverse Method....................................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

round Method......................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

search Method.....................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

setDate Method....................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

setHours Method.................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

setMonth Method................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

setSeconds Method..............................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

setTime Method...................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

What Is JScript?

vi

Page 9: What is JScript?

Table of ContentssetYear Method...................................................................................................................................................1

Arguments................................................................................................................................................1Remarks.............................................................................................................................................1

sin Method...........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

slice Method (Array)...........................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

slice Method (String)...........................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

small Method.......................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

sort Method..........................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

split Method.........................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

sqrt Method.........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

strike Method......................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

sub Method..........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

substr Method......................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

substring Method................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

sup Method..........................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

What Is JScript?

vii

Page 10: What is JScript?

Table of Contentstan Method...........................................................................................................................................................1

Remarks...................................................................................................................................................1Requirements.....................................................................................................................................1

test Method..........................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

toGMTString Method.........................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

toLocaleString Method.......................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

toLowerCase Method..........................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

toUpperCase Method..........................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

ubound Method...................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

unescape Method.................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

Array Object........................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

arguments Object................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Date Object..........................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Global Object......................................................................................................................................................1Remarks...................................................................................................................................................1

Properties...........................................................................................................................................1

Math Object.........................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

What Is JScript?

viii

Page 11: What is JScript?

Table of ContentsRegular Expression Object................................................................................................................................1

Syntax 1...................................................................................................................................................1Syntax 2.............................................................................................................................................1

String Object.......................................................................................................................................................1Syntax......................................................................................................................................................1

Arguments.........................................................................................................................................1

Addition Assignment Operator (+=).................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Bitwise AND Assignment Operator (&=).........................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Bitwise AND Operator (&)................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Bitwise Left Shift Operator (<<)........................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Bitwise NOT Operator (~)..................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Bitwise OR Assignment Operator (|=)..............................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Bitwise OR Operator (|)......................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Bitwise Right Shift Operator (>>).....................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Bitwise XOR Assignment Operator (^=)..........................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Bitwise XOR Operator (^).................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Comma Operator (,)...........................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

What Is JScript?

ix

Page 12: What is JScript?

Table of ContentsComparison Operators.......................................................................................................................................1

Arguments................................................................................................................................................1Remarks.............................................................................................................................................1

Conditional (Ternary) Operator (?:)................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

delete Operator....................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

Division Assignment Operator (/=)....................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Increment (++) and Decrement ( � ) Operators...............................................................................................1Syntax 1...................................................................................................................................................1

Syntax 2.............................................................................................................................................1

instanceof Operator............................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Left Shift Assignment Operator (<<=)..............................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Modulus Assignment Operator (%=)................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Modulus Operator (%).......................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Multiplication Assignment Operator (*=)........................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Multiplication Operator (*)...............................................................................................................................1Arguments................................................................................................................................................1

Requirements.....................................................................................................................................1

new Operator.......................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Right Shift Assignment Operator (>>=)...........................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

What Is JScript?

x

Page 13: What is JScript?

Table of ContentsSubtraction Assignment Operator (-=).............................................................................................................1

Arguments................................................................................................................................................1Remarks.............................................................................................................................................1

typeof Operator...................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

Unsigned Right Shift Operator (>>>)...............................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Unsigned Right Shift Assignment Operator (>>>=)........................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

void Operator......................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

0...n Properties.....................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

$1...$9 Properties.................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

callee Property.....................................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

constructor Property..........................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

E Property............................................................................................................................................................1Requirements...........................................................................................................................................1

See Also.............................................................................................................................................1

index Property.....................................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

input Property ($_).............................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

length Property (arguments)..............................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

What Is JScript?

xi

Page 14: What is JScript?

Table of Contentslength Property (Array).....................................................................................................................................1

Arguments................................................................................................................................................1Remarks.............................................................................................................................................1

length Property (Function).................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

length Property (String).....................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

LN10 Property.....................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

LN2 Property.......................................................................................................................................................1Syntax......................................................................................................................................................1

Requirements.....................................................................................................................................1

LOG10E Property...............................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

LOG2E Property.................................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

PI Property..........................................................................................................................................................1Syntax......................................................................................................................................................1

Requirements.....................................................................................................................................1

prototype Property..............................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

source Property...................................................................................................................................................1Requirements...........................................................................................................................................1

See Also.............................................................................................................................................1

SQRT1_2 Property.............................................................................................................................................1Remarks...................................................................................................................................................1

Requirements.....................................................................................................................................1

SQRT2 Property.................................................................................................................................................1Syntax......................................................................................................................................................1

Requirements.....................................................................................................................................1

undefined Property.............................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

What Is JScript?

xii

Page 15: What is JScript?

Table of Contents@cc_on Statement...............................................................................................................................................1

Remarks...................................................................................................................................................1Requirements.....................................................................................................................................1

@if Statement......................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

@set Statement....................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

break Statement..................................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

Comment Statements..........................................................................................................................................1Syntax 1...................................................................................................................................................1

Syntax 2.............................................................................................................................................1

continue Statement..............................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

do...while Statement............................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

for Statement.......................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

for...in Statement.................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

function Statement..............................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

if...else Statement.................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Labeled Statement..............................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

return Statement.................................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

What Is JScript?

xiii

Page 16: What is JScript?

Table of Contentsswitch Statement.................................................................................................................................................1

Arguments................................................................................................................................................1Remarks.............................................................................................................................................1

this Statement......................................................................................................................................................1Remarks...................................................................................................................................................1

Example.............................................................................................................................................1

try...catch�finally Statement..............................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

var Statement......................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

while Statement...................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

with Statement.....................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

VBScript User's Guide.......................................................................................................................................1

Adding VBScript Code to an HTML Page.......................................................................................................1The <SCRIPT> Tag.................................................................................................................................1

A Simple VBScript Page.....................................................................................................................................1A Simple Page.........................................................................................................................................1

Other Ways to Attach Code to Events...............................................................................................1

VBScript and Forms...........................................................................................................................................1Simple Validation....................................................................................................................................1

Using Numeric Values......................................................................................................................1

Using VBScript with Objects.............................................................................................................................1Using Objects...........................................................................................................................................1

VBScript Language Reference...........................................................................................................................1

Count Property....................................................................................................................................................1Remarks...................................................................................................................................................1

See Also.............................................................................................................................................1

Item Property......................................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

What Is JScript?

xiv

Page 17: What is JScript?

Table of ContentsKey Property.......................................................................................................................................................1

Arguments................................................................................................................................................1Remarks.............................................................................................................................................1

Add Method (Dictionary)...................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Column Property................................................................................................................................................1Remarks...................................................................................................................................................1

See Also.............................................................................................................................................1

Line Property......................................................................................................................................................1Remarks...................................................................................................................................................1

See Also.............................................................................................................................................1

Add Method (Folders)........................................................................................................................................1Arguments................................................................................................................................................1

Remarks.............................................................................................................................................1

Count Property....................................................................................................................................................1Remarks...................................................................................................................................................1

See Also.............................................................................................................................................1

Script Components..............................................................................................................................................1

Script Components Overview............................................................................................................................1

Introducing Windows Script Components.......................................................................................................1See Also...................................................................................................................................................1

How Script Components Work..........................................................................................................................1See Also...................................................................................................................................................1

Script Component File Contents.......................................................................................................................1Skeleton Script Component File..............................................................................................................2

See Also.............................................................................................................................................3

Using the Script Component Wizard................................................................................................................1See Also...................................................................................................................................................1

Creating Registration Information...................................................................................................................1Running Script During Registration........................................................................................................2Registering for Remote Access................................................................................................................2

See Also.............................................................................................................................................3

Exposing Methods...............................................................................................................................................1See Also...................................................................................................................................................2

Exposing Properties............................................................................................................................................1See Also...................................................................................................................................................3

What Is JScript?

xv

Page 18: What is JScript?

Table of ContentsExposing Events..................................................................................................................................................1

Declaring Events......................................................................................................................................1Specifying Dispatch Identifiers................................................................................................................1Firing an Event.........................................................................................................................................2

See Also.............................................................................................................................................2

Creating a Script Component Type Library....................................................................................................1Generating Type Libraries Dynamically.................................................................................................1Command-line Interface..........................................................................................................................2Troubleshooting Type Libraries..............................................................................................................3

See Also.............................................................................................................................................3

Referencing Other Components........................................................................................................................1Referencing Additional COM Components.............................................................................................1Referencing an External Type Library....................................................................................................1Referencing Resources.............................................................................................................................1

See Also.............................................................................................................................................2

Referencing Another Script Component in the Same Package......................................................................1See Also...................................................................................................................................................2

Checking For Errors in Script Component Files.............................................................................................1Setting Error Options...............................................................................................................................1

See Also.............................................................................................................................................1

Using a Script Component in an Application...................................................................................................1Creating Local Instances of Script Components......................................................................................1Creating Remote Instances of Script Components..................................................................................2

See Also.............................................................................................................................................3

Handling Script Component Events in the Host Application.........................................................................1See Also...................................................................................................................................................1

Creating a Behavior Script Component...........................................................................................................1Creating a Behavior Script Component File............................................................................................1Behavior-Related Enhancements to the DHTML Object Model.............................................................2Getting Event Parameters in the Script Component................................................................................3Scope Rules..............................................................................................................................................3Timing Considerations.............................................................................................................................4

See Also.............................................................................................................................................4

Exposing Properties and Methods in Behavior Script Components..............................................................1Exposing a Property.................................................................................................................................1Exposing a Method..................................................................................................................................1

See Also.............................................................................................................................................1

Exposing Custom Events in Behavior Script Components.............................................................................1Getting and Setting Custom Event Information......................................................................................1Example...................................................................................................................................................1

See Also.............................................................................................................................................2

What Is JScript?

xvi

Page 19: What is JScript?

Table of Contents<implements> Element.......................................................................................................................................1

Values......................................................................................................................................................1Remarks.............................................................................................................................................1

<property> Element............................................................................................................................................1Values......................................................................................................................................................1

Remarks.............................................................................................................................................1

<public> Element................................................................................................................................................1See Also...................................................................................................................................................1

<reference> Element...........................................................................................................................................1Values......................................................................................................................................................1

Remarks.............................................................................................................................................1

<registration> Element.......................................................................................................................................1Values......................................................................................................................................................1

Remarks.............................................................................................................................................1

<resource> Element............................................................................................................................................1Values......................................................................................................................................................1

Remarks.............................................................................................................................................1

<script> Element.................................................................................................................................................1Values......................................................................................................................................................1

Remarks.............................................................................................................................................1

<component> Element........................................................................................................................................1Values......................................................................................................................................................1

Remarks.............................................................................................................................................1

<attach> Element................................................................................................................................................1Values......................................................................................................................................................1

Example.............................................................................................................................................1

element Property.................................................................................................................................................1Values......................................................................................................................................................1

Remarks.............................................................................................................................................1

<layout> Element................................................................................................................................................1Values......................................................................................................................................................1

Remarks.............................................................................................................................................1

What Is JScript?

xvii

Page 20: What is JScript?

What Is JScript?

xviii

Page 21: What is JScript?

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 ofthe 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-fledgedobject-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, forexample), nor is it a simplification of anything. It is, however, limited. You cannot write stand-aloneapplications in it, for example, and it has no built-in support for reading or writing files. Moreover, JScriptscripts can run only in the presence of an interpreter or "host", such as Active Server Pages (ASP), InternetExplorer, or Windows Script Host.

JScript is a loosely typed language. Loosely typed means you do not have to declare the data types ofvariables explicitly. In fact, JScript takes it one step further. You cannot explicitly declare data types inJScript. Moreover, in many cases JScript performs conversions automatically when needed. For instance, ifyou 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 densethan 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 writingcode that you can read and easily understand six months after you write it.

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

What Is JScript? 1

Page 22: What is JScript?

2 What Is JScript?

2 What Is JScript?

Page 23: What is JScript?

Writing JScript CodeLike many other programming languages, Microsoft JScript is written in text format, and organized intostatements, blocks consisting of related sets of statements, and comments. Within a statement you can usevariables, 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 inEnglish. 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 iswritten on a single line, although a statement can be written over two or more lines. Also, two or morestatements can be written on the same line by separating them with semicolons. In general, each new linebegins a new statement. It is a good idea to terminate your statements explicitly. You do this with thesemicolon (;), which is the JScript statement termination character. Here are two examples of JScriptstatements.

aBird = "Robin"; // Assign the text "Robin" to the variable aBirdvar today = new Date(); // Assign today's date to the variable today

A group of JScript statements surrounded by braces ({}) is called a block. Statements grouped into a blockcan generally be treated as a single statement. This means you can use blocks in most places that JScriptexpects a lone statement. Notable exceptions include the headers of for and while loops. Notice that theprimitive 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 followingexample, 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 linecomment.

aGoodIdea = "Comment your code thoroughly."; // This is 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.

The statement assigns a value to the aGoodIdea variable. The value,

Writing JScript Code 1

Page 24: What is JScript?

which is contained between the quote marks, is called a literal. A literal explicitly and directly contains information; it does not refer to the information indirectly. The quote marks are not part of the literal.*/

Note If you attempt to embed one multiline comment within another, JScript interprets theresulting multiline comment in an unexpected way. The */ that marks the end of theembedded multiline comment is interpreted as the end of the whole multiline comment. Thismeans 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 tocomment out large segments of code with a multiline comment later.

// This is another multiline comment, written as a series of single-line comments.// After the statement is executed, you can refer to the content of the aGoodIdea// variable by using its name, as in the next statement, in which a string literal is// appended to the aGoodIdea variable by concatenation to create a new variable.

var extendedIdea = aGoodIdea + " You never know when you'll have to figure out what it does.";

Assignments and Equality

The equal sign (=) is used in JScript statements to assign values to variables: it is the assignment operator. Theleft hand operand of the = operator is always an Lvalue. Examples of Lvalues are:

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 isdiscussed 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. Thevalue can be of any valid JScript type - a number, a string, an object, and so on. The simplest expressions areliterals. Here are some examples of JScript literal expressions.

3.9 // numeric literal"Hello!" // string literalfalse // boolean literalnull // literal null value{x:1, y:2} // Object literal[1,2,3] // Array literalfunction(x){return x*x;} // function literal

2 Writing JScript Code

2 Writing JScript Code

Page 25: What is JScript?

More complicated expressions can contain variables, function calls, and other expressions. You can combineexpressions to create complex expressions using operators. Examples of operators are:

+ // additon- // subtraction* // multiplication/ // division

Here are some examples of JScript complex expressions.

var anExpression = 3 * (4 / 5) + 6;var aSecondExpression = Math.PI * radius * radius;var aThirdExpression = aSecondExpression + "%" + anExpression;var aFourthExpression = "(" + aSecondExpression + ") % (" + anExpression + ")";

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Writing JScript Code 3

Writing JScript Code 3

Page 26: What is JScript?

4 Writing JScript Code

4 Writing JScript Code

Page 27: What is JScript?

JScript VariablesIn any programming language, a piece of data is used to quantify a concept.

How old am I?

In JScript, a variable is the name you give that concept; it represents the value at a given instant. When youuse the variable, you really mean the data it represents. Here is an example:

NumberOfDaysLeft = EndDate � TodaysDate;

In a mechanical sense, you use variables to store, retrieve, and manipulate all the different values that appearin your scripts. Always create a meaningful variable name; that makes it easy for humans to understand whatyour 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 inmemory so you can refer to it later on in your script. Always declare variables before using them. You do thisusing the var keyword.

var count; // a single declaration.var count, amount, level; // multiple declarations with a single var keyword.var count = 0, amount = 100; // variable declaration and initialization in one statement.

If you do not initialize your variable in the var statement, it automatically takes on the JScript valueundefined. Although it is unsafe to do so, it is legal JScript syntax to omit the var keyword from yourdeclaration statement. When you do, the JScript interpreter gives the variable global scope visibility. Whenyou declare a variable at the procedure level though, you do not want it to be visible at the global scope; inthis 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 thevariable name MYCounter. Variable names can be of any length. The rules for creating legal variable namesare 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.•

Here are some examples of valid variable names:

_pagecount Part9 Number_Items

JScript Variables 1

Page 28: What is JScript?

Here are some examples of invalid variable names:

99Balloons // Cannot begin with a number. Smith&Wesson // The ampersand (&) character is not a valid character for variable names.

When you want to declare a variable and initialize it, but do not want to give it any particular value, assign itthe JScript value null. Here is an example.

var bestAge = null;var muchTooOld = 3 * bestAge; // muchTooOld has the value 0.

If you declare a variable without assigning a value to it, it exists, but has the JScript value undefined. Here isan 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 valuewill 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 isan implicit declaration.

noStringAtAll = ""; // The variable noStringAtAll is declared implicitly.

You cannot use a variable that has never been declared.

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 numberand 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 tostrongly typed languages like C++). Instead, JScript variables have a type that corresponds to the type of valuethey contain. A benefit of this behavior is that it provides you with the flexibility to treat a value as if it wereof another type.

In JScript, you can perform operations on values of differing types without fear that the JScript interpreter willraise an exception. Instead, the JScript interpreter automatically changes (coerces) one of the data types to thatof the other, then performs the operation. For example:

Operation ResultAdd 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.

var x = 2000; // A number.var y = "Hello"; // A string.x = x + y; // the number is coerced into a string.document.write(x); // Outputs 2000Hello.

2 JScript Variables

2 JScript Variables

Page 29: What is JScript?

To explicitly convert a string to an integer, use the parseInt Method. To explicitly convert a string to anumber, use the parseFloat Method. Notice that strings are automatically converted to equivalent numbers forcomparison purposes, but are left as strings for addition (concatenation).

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

JScript Variables 3

JScript Variables 3

Page 30: What is JScript?

4 JScript Variables

4 JScript Variables

Page 31: What is JScript?

JScript Data TypesIn JScript, there are three primary data types, two composite data types, and two special data types.

The primary (primitive) data types are:

String• Number• Boolean•

The composite (reference) data types are:

Object• Array•

The special data types are:

Null• Undefined•

String Data Type

A string value is a chain of zero or more Unicode characters (letters, digits, and punctuation marks) strungtogether. You use the string data type to represent text in JScript. String literals can be included in your scriptsby enclosing them in matching pairs of single or double quotation marks. Double quotation marks can becontained within strings surrounded by single quotation marks, and single quotation marks can be containedwithin strings surrounded by double quotation marks. The following are examples of strings:

"Happy am I; from care I'm free!"'"Avast, ye lubbers!" roared the technician.' "42"'c'

Notice that JScript does not have a type to represent a single character. To represent a single character inJScript, you create a string that consists of only one character. A string that contains zero characters ("") is anempty (zero-length) string.

Number Data Type

In JScript, there is no distinction between integer and floating-point values; a JScript number can be either(internally, JScript represent all numbers as floating-point values).

Integer Values

Integer values can be positive whole numbers, negative whole numbers, and 0. They can be represented inbase 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 7only. 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 cancontain digits 0 through 9, and letters A through F (either uppercase or lowercase) only. The letters A throughF are used to represent, as single digits, 10 through 15 in base 10. That is, 0xF is equivalent to 15, and 0x10 isequivalent to 16.

JScript Data Types 1

Page 32: What is JScript?

Both octal and hexadecimal numbers can be negative, but cannot have a decimal portion, and cannot bewritten in scientific (exponential) notation.

Floating-point Values

Floating-point values can be whole numbers with a decimal portion. Additionally, they can be expressed inscientific notation. That is, an uppercase or lowercase "e" is used to represent "ten to the power of". JScriptrepresents numbers using the eight byte IEEE 754 floating-point standard for numerical representation. Thismeans you can write numbers as large as ±1.7976931348623157x10308, and as small as ±5x10-324. A numberthat 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. Hereare some examples of JScript numbers.

Number Description Decimal Equivalent.0001, 0.0001, 1e-4, 1.0e-4 Four equivalent floating-point numbers. 0.00013.45e2 A floating-point number. 34542 An integer. 420378 An integer. Although this looks like an octal

number (it begins with a zero), 8 is not a valid octaldigit, so the number is treated as a decimal.

378

0377 An octal integer. Notice that although it onlyappears to be one less than the number above, itsactual value is quite different.

255

0.0001 A floating point number. Even though this beginswith a zero, it is not an octal number because it hasa decimal point.

0.0001

00.0001 This is an error. The two leading zeros mark thenumber as an octal, but octals are not allowed adecimal component.

N/A (compiler error)

0Xff A hexadecimal integer. 2550x37CF A hexadecimal integer. 142870x3e7 A hexadecimal integer. Notice that the 'e' is not

treated as exponentiation.999

0x3.45e2 This is an error. Hexadecimal numbers cannot havedecimal parts.

N/A (compiler error)

Additionally, JScript contains numbers with special values. These are:

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

Boolean Data Type

Whereas the string and number data types can have a virtually unlimited number of different values, theBoolean data type can only have two. They are the literals true and false. A Boolean value is a truth-value �it expresses the validity of a condition (tells whether the condition is true or not).

2 JScript Data Types

2 JScript Data Types

Page 33: What is JScript?

Comparisons you make in your scripts always have a Boolean outcome. Consider the following line of JScriptcode.

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 thecomparison is the Boolean value true, which is assigned to the variable y. If x is not equal to 2000, then theresult of the comparison is the Boolean value false.

Boolean values are especially useful in control structures. Here, you combine a comparison that creates aBoolean 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 analternate 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 astrue. For example, you could use an expression such as:

if (x = y + z) // This may not do what you expect -- see below!

Note that the above line does not check if x is equal to y + z, since only a single equal sign (assignment) isused. Instead, the code above assigns the value of y + z to the variable x, and then checks if the result of theentire expression (the value of x) is zero. To check if x is equal to y + z, use the following code.

if (x == y + z) // This is different to the code above!

For more information on comparisons, see Controlling Program Flow.

Null Data Type

The null data type has only one value in JScript: null. The null keyword cannot be used as the name of afunction or variable.

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) byassigning 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 inJScript will report null values as being of type Object, not of type null. This potentially confusing behavior isfor backwards compatibility.

Undefined Data Type

The undefined value is returned when you use:

an object property that does not exist,• a variable that has been declared, but has never had a value assigned to it.•

JScript Data Types 3

JScript Data Types 3

Page 34: What is JScript?

Notice that you cannot test to see if a variable exists by comparing it to undefined, although you can check ifits type is "undefined". In the following code example, assume that the programmer is trying to test if thevariable x has been declared:

// This method will not workif (x == undefined) // do something

// This method also won't work - you must check for// the string "undefined"if (typeof(x) == undefined) // do something

// This method will workif (typeof(x) == "undefined") // do something

Consider comparing the undefined value to null.

someObject.prop == null;

This comparison is true,

if the property someObject.prop contains the value null,• if the property someObject.prop does not exist.•

To check if an object property exists, you can use the new in operator:

if ("prop" in someObject) // someObject has the property 'prop'

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

4 JScript Data Types

4 JScript Data Types

Page 35: What is JScript?

JScript OperatorsJScript has a full range of operators, including arithmetic, logical, bitwise, assignment, as well as somemiscellaneous operators.

Computational Operators

Description SymbolUnary negation -Increment ++Decrement �Multiplication *Division /Modulus arithmetic %Addition +Subtraction -Logical Operators

Description SymbolLogical 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 SymbolBitwise NOT ~Bitwise Left Shift <<Bitwise Right Shift >>Unsigned Right Shift >>>Bitwise AND &Bitwise XOR ^Bitwise OR |Assignment Operators

Description SymbolAssignment =

JScript Operators 1

Page 36: What is JScript?

Compound Assignment OP=Miscellaneous Operators

Description Symboldelete deletetypeof typeofvoid voidinstanceof instanceofnew newin inThe difference between == (equality) and === (strict equality) is that the equality operator will coerce valuesof different types before checking for equality. For example, comparing the string "1" with the number 1 willcompare as true. The strict equlity operator, on the other hand, will not coerce values to different types, and sothe 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 willcompare as equal. Objects (including Array, Function, String, Number, Boolean, Error, Date and RegExpobjects) compare by reference. Even if two variables of these types have the same value, they will onlycompare as true if they refer to exactly the same object.

For example:

// Two primitive strings with the same value.var string1 = "Hello";var string2 = "Hello";

// Two String objects, with the same value.var StringObject1 = new String(string1);var StringObject2 = new String(string2);

// This will be true.if (string1 == string2) // do something (this will be executed)

// This will be false.if (StringObject1 == StringObject2) // do something (this will not be executed)

// To compare the value of String objects, // use the toString() or valueOf() methods.if (StringObject1.valueOf() == StringObject2) // do something (this will be executed)

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 JScript Operators

2 JScript Operators

Page 37: What is JScript?

Controlling Program FlowNormally, 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 controlis based upon a decision, the result of which is a truth statement (returning a Boolean true or false). Youcreate an expression, then test whether its result is true. There are two main kinds of program structures thataccomplish this.

The first is the selection structure. You use it to specify alternate courses of program flow, creating a junctionin your program (like a fork in a road). There are four selection structures available in JScript.

the single-selection structure (if),• the double-selection structure (if/else),• the inline ternary operator ?:• the multiple-selection structure (switch).•

The second type of program control structure is the repetition structure. You use it to specify that an action isto 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 repetitionstructure. There are four repetition structures available in JScript.

the expression is tested at the top of the loop (while),• the expression is tested at the bottom of the loop (do/while),• operate on each of an object's properties (for/in).• counter controlled repetition (for).•

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

Using Conditional Statements

JScript supports if and if...else conditional statements. In if statements a condition is tested, and if thecondition meets the test, the relevant JScript code is executed. In the if...else statement, different code isexecuted if the condition fails the test. The simplest form of an if statement can be written on one line, butmultiline if and if...else statements are much more common.

The following examples demonstrate syntaxes you can use with if and if...else statements. The first exampleshows the simplest kind of Boolean test. If (and only if) the item between the parentheses evaluates to (or canbe coerced to) true, the statement or block of statements after the if is executed.

// The smash() function is defined elsewhere in the code.// Boolean test of whether newShip is true.if (newShip) smash(champagneBottle,bow);

// In this example, the test fails unless both conditions are true.if (rind.color == "deep yellow " && rind.texture == "large and small wrinkles"){

Controlling Program Flow 1

Page 38: What is JScript?

theResponse = ("Is it a Crenshaw melon?");}

// In this example, the test succeeds if either condition is true.var theReaction = "";if ((dayOfWeek == "Saturday") || (dayOfWeek == "Sunday")){ theReaction = ("I'm off to the beach!");}else{ theReaction = ("Hi ho, hi ho, it's off to work I go!");}

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 conditionis met and one if it is not. A colon must separate these alternatives.

var hours = "";

// Code specifying that hours contains either the contents of// theHour, or theHour - 12.

hours += (theHour >= 12) ? " PM" : " AM";

If you have several conditions to be tested together, and you know that one is more likely to pass or fail thanthe others, you can use a feature called 'short circuit evaluation' to speed the execution of your script. WhenJScript 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 is123. If it is not, the entire expression cannot be true, even if y is equal to 42. Hence, the test for y is nevermade, and JScript returns the value false.

Similarly, if only one of several conditions must be true (using the || operator), testing stops as soon as anyone condition passes the test. This is effective if the conditions to be tested involve the execution of functioncalls or other complex expressions. With this in mind, when you write Or expressions, place the conditionsmost 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 followingexample if runfirst() returns 0 or false.

if ((runfirst() == 0) || (runsecond() == 0)) { // some code}

Using Loops

There are several ways to execute a statement or block of statements repeatedly. In general, repetitiveexecution is called looping or iteration. An iteration is simply a single execution of a loop. It is typicallycontrolled by a test of a variable, where the value of which is changed each time the loop is executed. JScriptsupports four types of loops: for loops, for...in loops, while loops, do...while loops.

2 Controlling Program Flow

2 Controlling Program Flow

Page 39: What is JScript?

Using for Loops

The for statement specifies a counter variable, a test condition, and an action that updates the counter. Beforeeach iteration of the loop, the condition is tested. If the test is successful, the code inside the loop is executed.If the test is unsuccessful, the code inside the loop is not executed, and the program continues on the first lineof code immediately following the loop. After the loop is executed, the counter variable is updated before thenext iteration begins.

If the condition for looping is never met, the loop is never executed. If the test condition is always met, aninfinite loop results. While the former may be desirable in certain cases, the latter rarely is, so be cautiouswhen 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 thebody of the loop is executed, and before the condition is tested.*/

var howFar = 10; // Sets a limit of 10 on the loop.

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 not greater than howFarnewSum += icount;}

var sum = 0;for(var icount = 0; icount >= 0; icount++) { // This is an infinite loop.sum += icount;}

Using for...in Loops

JScript provides a special kind of loop for stepping through all the user-defined properties of an object, or allthe elements of an array. The loop counter in a for...in loop is a string, not a number. It contains the name ofcurrent property or the index of the current array element.

The following code sample should be run from within Internet Explorer, since it uses the alert method, whichis not a part of JScript.

// Create an object with some propertiesvar myObject = new Object();myObject.name = "James";myObject.age = "22";myObject.phone = "555 1234";

// Enumerate (loop through)_all the properties in the objectfor (prop in myObject){ // This displays "The property 'name' is James", etc. window.alert("The property '" + prop + "' is " + myObject[prop]);}

Controlling Program Flow 3

Controlling Program Flow 3

Page 40: What is JScript?

Although for...in loops look similar to VBScript's For Each...Next loops, they do not work the same way.The JScript for...in loop iterates over properties of JScript objects. The VBScript For Each...Next loopiterates over items in a collection. To loop over collections in JScript, you need to use the Enumerator object.Although some objects, such as those in Internet Explorer, support both VBScript's For Each...Next andJScript's for...in loops, most objects do not.

Using while Loops

A while loop is similar to a for loop. The difference is, a while loop does not have a built-in counter variableor update expression. If you want to control repetitive execution of a statement or block of statements, butneed a more complex rule than simply "run this code n times", use a while loop. The following example usesthe Internet Explorer object model and a while loop to ask the user a simple question.

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 morevulnerable to infinite looping than the other types of loops. Moreover, because it is notnecessarily easy to discover where or when the loop condition is updated, it is easy to write awhile loop in which the condition never gets updated. For this reason, you should be carefulwhen 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 isguaranteed to always execute at least once, since the condition is tested at the end of the loop, rather than atthe 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!");

Using break and continue Statements

In Microsoft JScript, the break statement is used to stop the execution of a loop, if some condition is met.(Note that break is also used to exit a switch block). The continue statement can be used to jump immediatelyto the next iteration, skipping the rest of the code block, while updating the counter variable if the loop is a foror for...in loop.

The following example builds on the previous example to use the break and continue statements to controlthe loop.

var x = 0;do{

4 Controlling Program Flow

4 Controlling Program Flow

Page 41: What is JScript?

x = window.prompt("What is my favourite number?", x);

// Did the user cancel? If so, break out of the loop if (x == null) break;

// Did they enter a number? // If so, no need to ask them to enter a number. if (Number(x) == x) continue;

// Ask user to only enter in numbers window.alert("Please only enter in numbers!");

} while (x != 42)

if (x == null) window.alert("You gave up!");else window.alert("Yep - it's the Ultimate Answer!");

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Controlling Program Flow 5

Controlling Program Flow 5

Page 42: What is JScript?

6 Controlling Program Flow

6 Controlling Program Flow

Page 43: What is JScript?

JScript ObjectsJScript objects are collections of properties and methods. A method is a function that is a member of anobject. A property is a value or set of values (in the form of an array or object) that is a member of an object.JScript supports four kinds of objects: intrinsic objects, objects you create, host objects, which are provided bythe host (such as window and document in Internet Explorer) and Active X objects (external components).

Objects as Arrays

In JScript, objects and arrays are handled almost identically. Both can have arbitrary properties assigned tothem, and indeed Arrays are merely a special kind of Object. The difference between Arrays and Objects isthat arrays have a "magic" length property, whilst objects do not. This means that if you assign a value to anelement of an array that is greater than every other element � for example, myArray[100] = "hello" � thenthe length property will automatically be updated to be 101 (the new length). Similarly, if you modify thelength 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 dynamicallyat run time. These properties can have any name, including numbers. If the name of the property is a simpleidentifier<<ref for identifier rules>>, it can be written after the object name with a period, such as:

var myObj = new Object();

// Add two expando properties, 'name' and 'age'myObj.name = "Fred";myObj.age = 42;

If the name of the property is not a simple identifier, or it is not known at the time you write the script, youcan use an arbitrary expression inside square brackets to index the property. The names of all expandoproperties in JScript are converted to strings before being added to the object.

var myObj = new Object();

// Add two expando properties that cannot be written in the// object.property syntax.// The first contains invalid characters (spaces), so must be// written inside square brackets.myObj["not a valid identifier"] = "This is the property value";

// The second expando name is a number, so it also must// be placed inside square bracketsmyObj[100] = "100";

Traditionally, array elements are given numeric indices, starting at zero. It is these elements that interact withthe 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:

// An array with three elementsvar myArray = new Array(3);

// Add some datamyArray[0] = "Hello";myArray[1] = 42;myArray[2] = new Date(2000, 1, 1);

// This will display 3, the length of the arraywindow.alert(myArray.length);

// Add some expando propertiesmyArray.expando = "JScript!";

JScript Objects 1

Page 44: What is JScript?

myArray["another Expando"] = "Windows";

// This will still display 3, since the two expando properties// don't affect the length.window.alert(myArray.length);

Although JScript does not directly support multi-dimensional arrays, you can store any sort of data insidearray elements � including other arrays. So you can get the behavior of multi-dimensional arrays by storingarrays within the elements of another array. For example, the following code builds a multiplication table forthe numbers up to 5:

// Change this number for a bigger tablevar iMaxNum = 5;// Loop countersvar i, j;

// New array. Make it iMaxNum + 1 because arrays start// counting at zero, not 1.var MultiplicationTable = new Array(iMaxNum + 1);

// Loop for each major number (each row in the table)for (i = 1; i <= iMaxNum; i++){ // Create the columns in the table MultiplicationTable[i] = new Array(iMaxNum + 1);

// Fill the row with the results of the multiplication for (j = 1; j <= iMaxNum; j++) { MultiplicationTable[i][j] = i * j; }}

window.alert(MultiplicationTable[3][4]); // Displays 12window.alert(MultiplicationTable[5][2]); // Displays 10window.alert(MultiplicationTable[1][4]); // Displays 4

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 JScript Objects

2 JScript Objects

Page 45: What is JScript?

JScript Reserved WordsJScript has a number of reserved words that you cannot use as identifiers. Reserved words have a specificmeaning to the JScript language, as they are part of the language syntax. Using a reserved word causes acompilation 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

break delete function return typeofcase do if switch varcatch else in this voidcontinue false instanceof throw whiledebugger finally new true withdefault for null tryFuture Reserved Words

abstract double goto native staticboolean enum implements package superbyte export import private synchronizedchar extends int protected throwsclass final interface public transientconst float long short volatileWhen choosing identifiers it is also important to avoid any words that are already the names of intrinsicJScript objects or functions, such as String or parseInt.

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

JScript Reserved Words 1

Page 46: What is JScript?

2 JScript Reserved Words

2 JScript Reserved Words

Page 47: What is JScript?

Advanced Object CreationA constructor is a function you call to instantiate and initialize a particular type of object. You invoke aconstructor with the new keyword. Here are a few examples of using constructors.

var myObject = new Object(); // Creates a generic object with no properties.var myBirthday = new Date(1961, 5, 10); // Creates a Date object.var myCar = new Car(); // Creates a user defined object, and initializes its properties.

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 andgiving 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 constructorfunctions such as Object(), Date(), and Function(). A powerful feature of object-oriented programming is theability to define custom constructor functions to create custom objects for use in your scripts. You createcustom constructors so you can create objects with properties already defined. Here is an example of a customconstructor (note the use of the this keyword).

function Circle (xPoint, yPoint, radius) { this.x = xPoint; // The x component of the center of the circle. this.y = yPoint; // The y component of the center of the circle. this.r = radius; // The radius of the circle.}

When you invoke the Circle constructor, you supply values for the circle's center point and the radius (theseelements are all that is needed to completely define a unique circle object). You end up with a Circle objectthat contains three properties. Here is how you would instantiate a Circle object.

var aCircle = new Circle(5, 11, 99);

Using Prototypes to Create Objects

When you write a constructor, you can use properties of the prototype object (which is itself a property ofevery constructor) to create inherited properties, and shared methods. Prototype properties and methods arecopied by reference into each object of a class, so they all have the same values. You can change the value ofa prototype property in one object, and the new value overrides the default, but only in that one instance.Other objects that are members of the class are not affected by the change. Here is an example that makes useof the custom constructor, Circle (note the use of the this keyword).

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 a method of the Circle Prototype object.var a = ACircle.area(); // This is how you would invoke the area function on a Circle object.

Using this principle, you can define additional properties for predefined constructor functions (which all haveprototype 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, andall strings in your script will automatically inherit the method.

// Add a function called trim as a method of the prototype // object of the String constructor.

Advanced Object Creation 1

Page 48: What is JScript?

String.prototype.trim = function(){ // Use a regular expression to replace leading and trailing // spaces with the empty string return this.replace(/(^\s*)|(\s*$)/g, "");}

// A string with spaces in itvar s = " leading and trailing spaces ";

// Displays " leading and trailing spaces (35)"window.alert(s + " (" + s.length + ")");

// Remove the leading and trailing spacess = s.trim();// Displays "leading and trailing spaces (27)"window.alert(s + " (" + s.length + ")");

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 Advanced Object Creation

2 Advanced Object Creation

Page 49: What is JScript?

RecursionRecursion is an important programming technique. It is used to have a function call itself from within itself.One example is the calculation of factorials. The factorial of 0 is defined specifically to be 1. The factorials oflarger numbers are calculated by multiplying 1 * 2 * ..., incrementing by 1 until you reach the number forwhich you are calculating the factorial.

The following paragraph is a function, defined in words, that calculates a factorial.

"If the number is less than zero, reject it. If it is not an integer, round it down to the next integer. If the numberis zero, its factorial is one. If the number is larger than zero, multiply it by the factorial of the next lessernumber."

To calculate the factorial of any number that is larger than zero, you need to calculate the factorial of at leastone other number. The function you use to do that is the function you're in the middle of already; the functionmust call itself for the next smaller number, before it can execute on the current number. This is an example ofrecursion.

Recursion and iteration (looping) are strongly related - anything that can be done with recursion can be donewith 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 getto 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 verbaldescription 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 inorder to do that you first have to calculate the factorial of -26; and so on. Obviously, this never reaches astopping place.

Thus, it is extremely important to design recursive functions with great care. If you even suspect that there isany chance of an infinite recursion, you can have the function count the number of times it calls itself. If thefunction 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.

// Function to calculate factorials. If an invalid// number is passed in (ie, one less than zero), -1// is returned to signify an error. Otherwise, the// number is converted to the nearest integer, and its// factorial is returned.function factorial(aNumber) {aNumber = Math.floor(aNumber); // If the number is not an integer, round it down.if (aNumber < 0) { // If the number is less than zero, reject it. return -1; } if (aNumber == 0) { // If the number is 0, its factorial is 1. return 1; } else return (aNumber * factorial(aNumber - 1)); // Otherwise, recurse until done.}

© 2001 Microsoft Corporation. All rights reserved.

Recursion 1

Page 50: What is JScript?

Build: Topic Version 5.6.9309.1546

JScript

2 Recursion

2 Recursion

Page 51: What is JScript?

Variable ScopeJScript has two scopes: global and local. If you declare a variable outside of any function definition, it is aglobal variable, and its value is accessible and modifiable throughout your program. If you declare a variableinside of a function definition, that variable is local. It is created and destroyed every time the function isexecuted; 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. JScriptdoes 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 thelocal variable is declared, only the local version has meaning.

var aCentaur = "a horse with rider,"; // Global definition of aCentaur.

// JScript code, omitted for brevity.function antiquities() // A local aCentaur variable is declared in this function.{

// JScript code, omitted for brevity.var aCentaur = "A centaur is probably a mounted Scythian warrior";

// JScript code, omitted for brevity. aCentaur += ", misreported; that is, "; // Adds to the local variable.

// JScript code, omitted for brevity.} // End of the function.

var nothinginparticular = antiquities();aCentaur += " as seen from a distance by a naive innocent.";

/*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 existin. 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 with the name aNumber. 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.

} // End of the function definition.

When JScript executes a function, it first looks for all variable declarations,

var someVariable;

Variable Scope 1

Page 52: What is JScript?

and creates the variables with an initial value of undefined. If a variable is declared with a value,

var someVariable = "something";

then it still initially has the value undefined, and will take on the declared value only when the line containingthe declaration is executed, if ever.

JScript processes variable declarations before executing any code, so it does not matter whether thedeclaration is inside a conditional block or some other construct. Once JScript has found all the variables, itexecutes the code in the function. If a variable is implicitly declared inside a function - that is, if it appears onthe left-hand-side of an assignment expression but has not been declared with var - then it is created as aglobal variable.

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 Variable Scope

2 Variable Scope

Page 53: What is JScript?

Copying, Passing, and Comparing DataIn JScript, how data is handled depends on its data type.

By Value vs. By Reference

Numbers and Boolean values (true and false) are copied, passed, and compared by value. When you copy orpass by value, you allocate a space in computer memory and copy the value of the original into it. If you thenchange the original, the copy is not affected (and vice versa), because the two are separate entities.

Objects, arrays, and functions are copied, passed, and compared by reference. When you copy or pass byreference, you essentially create a pointer to the original item, and use the pointer as if it were a copy. If youthen change the original, you change both the original and the copy (and vice versa). There is really only oneentity; 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 tosucceed. For example, two distinct Array objects will always compare as unequal, even if they contain thesame elements. One of the variables must be a reference to the other one for the comparison to succeed. Tocheck 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 Stringobjects (created with new String("something")), they are compared by reference, but if one or both of thevalues is a string value, they are compared by value.

Note Because of the way the ASCII and ANSI character sets are constructed, capital lettersprecede 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 toperform a case-insensitive match.

Passing Parameters to Functions

When you pass a parameter to a function by value, you are making a separate copy of that parameter, a copythat exists only inside the function. Even though objects and arrays are passed by reference, if you directlyoverwrite them with a new value in the function, the new value is not reflected outside the function. Onlychanges to properties of objects, or elements of arrays, are visible outside the function.

For example (using the Internet Explorer object model):

// This clobbers (over-writes) its parameter, so the change// is not reflected in the calling code.function Clobber(param) { // clobber the parameter; this will not be seen in // the calling code param = new Object(); param.message = "This will not work";}

// This modifies a property of the parameter, which// can be seen in the calling code.function Update(param){ // Modify the property of the object; this will be seen // in the calling code. param.message = "I was changed";}

Copying, Passing, and Comparing Data 1

Page 54: What is JScript?

// Create an object, and give it a property.var obj = new Object();obj.message = "This is the original";

// Call Clobber, and print obj.message. Note that it hasn't changed.Clobber(obj);window.alert(obj.message); // Still displays "This is the original".

// Call Update, and print obj.message. Note that is has changed.Update(obj);window.alert(obj.message); // Displays "I was changed".

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 checkingto 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 arecreated, it becomes possible to compare them by value. This lets you test whether two strings have the samecontent even if one was generated entirely separately from the other.

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 Copying, Passing, and Comparing Data

2 Copying, Passing, and Comparing Data

Page 55: What is JScript?

Special CharactersJScript provides special characters that allow you to include in strings some characters you cannot typedirectly. Each of these characters begins with a backslash. The backslash is an escape character you use toinform the JScript interpreter that the next character is special.

Escape Sequence Character\b Backspace\f Form feed\n Line feed (newline)\r Carriage return\t Horizontal tab (Ctrl-I)\' Single quotation mark\" Double quotation mark\\ BackslashNotice that because the backslash itself is used as the escape character, you cannot directly type one in yourscript. If you want to write a backslash, you must type two of them together (\\).

document.write('The image path is C:\\webstuff\\mypage\\gifs\\garden.gif.');document.write('The caption reads, "After the snow of \'97. Grandma\'s house is covered."');

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Special Characters 1

Page 56: What is JScript?

2 Special Characters

2 Special Characters

Page 57: What is JScript?

Troubleshooting Your ScriptsThere are places in any programming language where you can get caught if you are not careful, and everylanguage has specific surprises in it. Take, for example, the null value: The one in JScript behaves differentlythan 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 paystrict attention to detail when you write scripts. If, for example, you mean for a particular parameter to be astring, you will run into trouble if you forget to enclose it in quotation marks when you type it.

Order of Script Interpretation

JScript interpretation is part of the your Web browser's HTML parsing process. So, if you place a script insidethe <HEAD> tag in a document, it is interpreted before any of the <BODY> tag is examined. If you haveobjects that are created in the <BODY> tag, they do not exist at the time the <HEAD> is being parsed, andcannot be manipulated by the script.

Note This behavior is specific to Internet Explorer. ASP and WSH have different executionmodels (as would other hosts).

Automatic Type Coercion

JScript is a loosely typed language with automatic coercion. Consequently, despite the fact that values havingdifferent types are not equal, the expressions in the following example evaluate to true.

"100" == 100;false == 0;

To check that both the type and value are the same, use the strict equality operator, ===. the following bothevaluate to false:

"100" === 100;false === 0;

Operator Precedence

When a particular operation is performed during the evaluation of an expression has more to do with operatorprecedence than with the location of the expression. Thus, in the following example, multiplication isperformed before subtraction, even though the subtraction appears first in the expression.

theRadius = aPerimeterPoint - theCenterpoint * theCorrectionFactor;

Using for...in Loops with Objects

When you step through the properties of an object with a for...in loop, you cannot necessarily predict orcontrol the order in which the fields of the object are assigned to the loop counter variable. Moreover, theorder may be different in different implementations of the language.

Troubleshooting Your Scripts 1

Page 58: What is JScript?

with Keyword

The with statement is convenient for addressing properties that already exist in a specified object, but cannotbe used to add properties to an object. To create new properties in an object, you must refer to the objectspecifically.

this Keyword

Although you use the this keyword inside the definition of an object, to refer to the object itself, you cannotordinarily use this or similar keywords to refer to the currently executing function when that function is not anobject definition. You can, if the function is to be assigned to an object as a method, use the this keywordwithin the function, to refer to the object.

Writing a Script That Writes a Script in Internet Explorer

The </SCRIPT> tag terminates the current script if the interpreter encounters it. To display "</SCRIPT>"itself, rewrite this as at least two strings, for example, "</SCR" and "IPT>", which you can then concatenatetogether in the statement that writes them out.

Implicit Window References in Internet Explorer

Because more than one window can be open at a time, any window reference that is implicit is taken to pointto the current window. For other windows, you must use an explicit reference.

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 Troubleshooting Your Scripts

2 Troubleshooting Your Scripts

Page 59: What is JScript?

Microsoft JScript Features - ECMAThe following table lists JScript features compliant with ECMA standards.

Category Feature/KeywordArray Handling Array

join, length, reverse, sortAssignments Assign (=)

Compound Assign (OP=)Booleans BooleanComments /*...*/ or //Constants/Literals NaN

nulltrue, falseInfinityundefined

Control flow Breakcontinueforfor...inif...elsereturnwhile

Dates and Time DategetDate, 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 Functionnewthisvarwith

Function Creation Functionarguments, length

Global Methods Globalescape, unescapeevalisFinite, isNaNparseInt, parseFloat

Math Mathabs, 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

Microsoft JScript Features - ECMA 1

Page 60: What is JScript?

NumberMAX_VALUE, MIN_VALUENaNNEGATIVE_INFINITY, POSITIVE_INFINITY

Object Creation Objectnewconstructor, 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, voidDecrement ( � ), Increment (++)

Objects ArrayBooleanDateFunctionGlobalMathNumberObjectString

Strings StringcharAt, charCodeAt, fromCharCodeindexOf, lastIndexOfsplittoLowerCase, toUpperCaselength

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 Microsoft JScript Features - ECMA

2 Microsoft JScript Features - ECMA

Page 61: What is JScript?

Microsoft JScript Features - Non-ECMAThe following table lists JScript features that are not compliant with ECMA standards.

Category Feature/KeywordArray Handling concat, slice

VBArraydimensions, getItem, lbound, toArray, ubound

Conditional Compilation @cc_on@if Statement@set StatementConditional Compilation Variables

Control flow do...whileLabeledswitch

Dates and Time getVarDateEnumeration Enumerator

atEnd, item, moveFirst, moveNextError Handling Error

description, numberthrow, try...catch

Function Creation callerOperators Identity (===), Nonidentity (!==)Objects Enumerator

RegExpRegular ExpressionVBArrayActiveXObjectGetObject

Regular Expressions and PatternMatching

RegExpindex, input, lastIndex, $1...$9, source, compile, exec, testRegular Expression Syntax

Script Engine Identification ScriptEngineScriptEngineBuildVersionScriptEngineMajorVersionScriptEngineMinorVersion

Strings concat, slicematch, replace, searchanchor, big, blink, bold, fixed, fontcolor, fontsize, italics, link, small,strike, sub, sup

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Microsoft JScript Features - Non-ECMA 1

Page 62: What is JScript?

2 Microsoft JScript Features - Non-ECMA

2 Microsoft JScript Features - Non-ECMA

Page 63: What is JScript?

abs MethodReturns the absolute value of a number.

Math.abs(number)

The required number argument is a numeric expression for which the absolute value is needed.

Remarks

The return value is the absolute value of the number argument.

Example

The following example illustrates the use of the abs method.

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

Math Object Methods

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

abs Method 1

Page 64: What is JScript?

2 abs Method

2 abs Method

Page 65: What is JScript?

acos MethodReturns the arccosine of a number.

Math.acos(number)

The required number argument is a numeric expression for which the arccosine is needed.

Remarks

The return value is the arccosine of the number argument.

Requirements

Version 1

See Also

asin Method | atan Method | cos Method | sin Method | tan Method

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

acos Method 1

Page 66: What is JScript?

2 acos Method

2 acos Method

Page 67: What is JScript?

anchor MethodPlaces an HTML anchor with a NAME attribute around specified text in the object.

strVariable.anchor(anchorString)

Arguments

strVariableRequired. Any String object or literal.

anchorStringRequired. 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 demonstrateshow the anchor method accomplishes this:

var strVariable = "This is an anchor";strVariable = strVariable.anchor("Anchor1");

The value of strVariable after the last statement is:

<A NAME="Anchor1">This is an anchor</A>

No checking is done to see if the tag has already been applied to the string.

Requirements

Version 1

See Also

link Method | String Object Methods | String Object Properties

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

anchor Method 1

Page 68: What is JScript?

2 anchor Method

2 anchor Method

Page 69: What is JScript?

asin MethodReturns the arcsine of a number.

Math.asin(number)

The required number argument is a numeric expression for which the arcsine is needed.

Remarks

The return value is the arcsine of its numeric argument.

Requirements

Version 1

See Also

acos Method | atan Method | cos Method | Math Object Methods | sin Method | tan Method

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

asin Method 1

Page 70: What is JScript?

2 asin Method

2 asin Method

Page 71: What is JScript?

atan MethodReturns the arctangent of a number.

Math.atan(number)

The required number argument is a numeric expression for which the arctangent is needed.

Remarks

The return value is the arctangent of its numeric argument.

Requirements

Version 1

See Also

acos Method | asin Method | atan2 Method | cos Method | Math Object Methods | sin Method | tan Method

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

atan Method 1

Page 72: What is JScript?

2 atan Method

2 atan Method

Page 73: What is JScript?

atan2 MethodReturns the angle (in radians) from the X axis to a point (y,x).

Math.atan2(y, x)

Arguments

xRequired. A numeric expression representing the cartesian x-coordinate.

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

atan Method | tan Method

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

atan2 Method 1

Page 74: What is JScript?

2 atan2 Method

2 atan2 Method

Page 75: What is JScript?

big MethodPlaces HTML <BIG> tags around text in a String object.

strVariable.big( )

The required strVariable reference is any String object or literal.

Remarks

The example that follows shows how the big method works:

var strVariable = "This is a string object";strVariable = strVariable.big( );

The value of strVariable after the last statement is:

<BIG>This is a string object</BIG>

No checking is done to see if the tag has already been applied to the string.

Requirements

Version 1

See Also

small Method | String Object Methods | String Object Properties

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

big Method 1

Page 76: What is JScript?

2 big Method

2 big Method

Page 77: What is JScript?

blink MethodPlaces HTML <BLINK> tags around text in a String object.

strVariable.blink( )

The required strVariable reference is any String object or literal.

Remarks

The following example demonstrates how the blink method works:

var strVariable = "This is a string object";strVariable = strVariable.blink( );

The value of strVariable after the last statement is:

<BLINK>This is a string object</BLINK>

No checking is done to see if the tag has already been applied to the string.

The <BLINK> tag is not supported in Microsoft Internet Explorer.

Requirements

Version 1

See Also

String Object Methods | String Object Properties

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

blink Method 1

Page 78: What is JScript?

2 blink Method

2 blink Method

Page 79: What is JScript?

bold MethodPlaces HTML <B> tags around text in a String object.

strVariable.bold()

The required strVariable reference is any String object or literal.

Remarks

The following example demonstrates how the bold method works:

var strVariable = "This is a string object";strVariable = strVariable.bold( );

The value of strVariable after the last statement is:

<B>This is a string object</B>

No checking is done to see if the tag has already been applied to the string.

Requirements

Version 1

See Also

italics Method | String Object Methods | String Object Properties

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

bold Method 1

Page 80: What is JScript?

2 bold Method

2 bold Method

Page 81: What is JScript?

ceil MethodReturns the smallest integer greater than or equal to its numeric argument.

Math.ceil(number)

The required number argument is a numeric expression.

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

floor Method | Math Object Methods

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

ceil Method 1

Page 82: What is JScript?

2 ceil Method

2 ceil Method

Page 83: What is JScript?

charAt MethodReturns the character at the specified index.

strObj.charAt(index)

Arguments

strObjRequired. Any String object or literal.

indexRequired. Zero-based index of the desired character. Valid values are between 0 and the length of thestring minus 1.

Remarks

The charAt method returns a character value equal to the character at the specified index. The first characterin a string is at index 0, the second is at index 1, and so forth. Values of index out of valid range return anempty string.

Example

The following example illustrates the use of the charAt method:

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

String Object Methods | String Object Properties

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

charAt Method 1

Page 84: What is JScript?

2 charAt Method

2 charAt Method

Page 85: What is JScript?

compile MethodCompiles a regular expression into an internal format for faster execution.

rgExp.compile(pattern, [flags])

Arguments

rgExpRequired. An instance of a Regular Expression object. Can be a variable name or a literal.

patternRequired. A string expression containing a regular expression pattern to be compiled

flagsOptional. 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 moreefficient use of regular expressions in loops, for example. A compiled regular expression speeds things upwhen reusing the same expression repeatedly. No advantage is gained, however, if the regular expressionchanges.

Example

The following example illustrates the use of the compile method:

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

Applies To: Regular Expression Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

compile Method 1

Page 86: What is JScript?

JScript

2 compile Method

2 compile Method

Page 87: What is JScript?

concat Method (Array)Returns a new array consisting of a combination of two or more arrays.

array1.concat([item1[, item2[, . . . [, itemN]]]])

Arguments

array1Required. The Array object to which all other arrays are concatenated.

item1,. . ., itemNOptional. 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 supplieditems.

The items to be added (item1 � itemN) to the array are added, in order, from left to right. If one of the items isan array, its contents are added to the end of array1. If the item is anything other than an array, it is added tothe end of the array as a single array element.

Elements of source arrays are copied to the resulting array as follows:

For an object reference copied from any of the arrays being concatenated to the new array, the objectreference continues to point to the same object. A change in either the new array or the original arraywill result in a change to the other.

For a numeric or string value being concatenated to the new array, only the value is copied. Changesin 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

concat Method (String) | join Method | String Object

Applies To: Array Object

concat Method (Array) 1

Page 88: What is JScript?

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 concat Method (Array)

2 concat Method (Array)

Page 89: What is JScript?

concat Method (String)Returns a string value containing the concatenation of two or more supplied strings.

string1.concat([string2[, string3[, . . . [, stringN]]]])

Arguments

string1Required. The String object or literal to which all other specified strings are concatenated.

string2,. . ., stringNOptional. 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 changeof value in either a source or result string does not affect the value in the other string. If any of the argumentsare 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

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

concat Method (String) 1

Page 90: What is JScript?

2 concat Method (String)

2 concat Method (String)

Page 91: What is JScript?

cos MethodReturns the cosine of a number.

Math.cos(number)

The required number argument is a numeric expression for which the cosine is needed.

Remarks

The return value is the cosine of its numeric argument.

Requirements

Version 1

See Also

acos Method | asin Method | atan Method | Math Object Methods | sin Method | tan Method

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

cos Method 1

Page 92: What is JScript?

2 cos Method

2 cos Method

Page 93: What is JScript?

dimensions MethodReturns the number of dimensions in a VBArray.

array.dimensions( )

The required array is a VBArray object.

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 safearray. The second part is JScript code that determines the number of dimensions in the safe array and theupper bound of each dimension. Both of these parts go into the <HEAD> section of an HTML page. The thirdpart 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 = aEnd 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

Page 94: What is JScript?

Requirements

Version 3

See Also

getItem Method | lbound Method | toArray Method | ubound Method

Applies To: VBArray Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 dimensions Method

2 dimensions Method

Page 95: What is JScript?

escape MethodEncodes String objects so they can be read on all computers.

escape(charString)

The required charString argument is any String object or literal to be encoded.

Remarks

The escape method returns a string value (in Unicode format) that contains the contents of charstring. Allspaces, punctuation, accented characters, and any other non-ASCII characters are replaced with %xxencoding, where xx is equivalent to the hexadecimal number representing the character. For example, a spaceis 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

encodeURI Method | encodeURIComponent Method | String Object | unescape Method

Applies To: Global Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

escape Method 1

Page 96: What is JScript?

2 escape Method

2 escape Method

Page 97: What is JScript?

eval MethodEvaluates JScript code and executes it.

eval(codeString)

The required codeString argument is a string value that contains valid JScript code. This string is parsed bythe JScript parser and executed.

Remarks

The eval function allows dynamic execution of JScript source code. For example, the following code creates anew variable mydate that contains a Date object:

eval("var mydate = new Date();");

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

Applies To: Global Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

eval Method 1

Page 98: What is JScript?

2 eval Method

2 eval Method

Page 99: What is JScript?

exec MethodExecutes a search on a string using a regular expression pattern, and returns an array containing the results ofthat search.

rgExp.exec(str)

Arguments

rgExpRequired. An instance of a Regular Expression object containing the regular expression pattern andapplicable flags.

strRequired. 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 theproperties of the global RegExp object are updated to reflect the results of the match. Element zero of thearray contains the entire match, while elements 1 � n contain any submatches that have occurred within thematch. 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 bythe value of lastIndex. If the global flag is not set, exec ignores the value of lastIndex and searches from thebeginning of the string.

The array returned by the exec method has three properties, input, index and lastIndex. The input propertycontains the entire searched string. The index property contains the position of the matched substring withinthe complete searched string. The lastIndex property contains the position following the last character in thematch.

Example

The following example illustrates the use of the exec method:

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

Page 100: What is JScript?

See Also

match Method | RegExp Object | Regular Expression Object Methods | Regular Expression Object Properties |Regular Expression Syntax | search method | test Method

Applies To: Regular Expression Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 exec Method

2 exec Method

Page 101: What is JScript?

exp MethodReturns e (the base of natural logarithms) raised to a power.

Math.exp(number)

The required number argument is numeric expression representing the power of e.

Remarks

The return value is enumber. The constant e is Euler's constant, approximately equal to 2.178 and number is thesupplied argument.

Requirements

Version 1

See Also

E Property | Math Object Methods

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

exp Method 1

Page 102: What is JScript?

2 exp Method

2 exp Method

Page 103: What is JScript?

fixed MethodPlaces HTML <TT> tags around text in a String object.

strVariable.fixed( )

The required strVariable reference is any String object or literal.

Remarks

The following example demonstrates how the fixed method works:

var strVariable = "This is a string object";strVariable = strVariable.fixed();

The value of strVariable after the last statement is:

<TT>This is a string object</TT>

No checking is done to see if the tag has already been applied to the string.

Requirements

Version 1

See Also

String Object Methods | String Object Properties

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

fixed Method 1

Page 104: What is JScript?

2 fixed Method

2 fixed Method

Page 105: What is JScript?

floor MethodReturns the greatest integer less than or equal to its numeric argument.

Math.floor(number)

The required number argument is a numeric expression.

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

ceil Method | Math Object Methods

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

floor Method 1

Page 106: What is JScript?

2 floor Method

2 floor Method

Page 107: What is JScript?

fontcolor MethodPlaces an HTML <FONT> tag with the COLOR attribute around the text in a String object.

strVariable.fontcolor(colorVal)

Arguments

strVariableRequired. Any String object or literal.

colorValRequired. String value containing a color value. This can either be the hexadecimal value for a color,or the predefined name for a color.

Remarks

The following example demonstrates the fontcolor method:

var strVariable = "This is a string";strVariable = strVariable.fontcolor("red");

The value of strVariable after the last statement is:

<FONT COLOR="RED">This is a string</FONT>

Valid predefined color names depend on your JScript host (browser, server, and so forth). They may also varyfrom 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

fontsize Method | String Object Methods | String Object Properties

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

fontcolor Method 1

Page 108: What is JScript?

2 fontcolor Method

2 fontcolor Method

Page 109: What is JScript?

fontsize MethodPlaces an HTML <FONT> tag with the SIZE attribute around the text in a String object.

strVariable.fontsize(intSize)

Arguments

strVariableRequired. Any String object or literal.

intSizeRequired. Integer value that specifies the size of the text.

Remarks

The following example demonstrates the fontsize method:

var strVariable = "This is a string";strVariable = strVariable.fontsize(-1);

The value of strVariable after the last statement is:

<FONT SIZE="-1">This is a string</FONT>

Valid integer values depend on your Microsoft JScript host. See your host documentation for moreinformation.

No checking is done to see if the tag has already been applied to the string.

Requirements

Version 1

See Also

fontcolor Method | String Object Methods | String Object Properties

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

fontsize Method 1

Page 110: What is JScript?

2 fontsize Method

2 fontsize Method

Page 111: What is JScript?

getDate MethodReturns the day of the month value in a Date object using local time.

dateObj.getDate()

The required dateObj reference is a Date object.

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

The following example illustrates the use of the getDate method.

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

Date Object Methods | getUTCDate Method | setDate Method | setUTCDate Method

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

getDate Method 1

Page 112: What is JScript?

2 getDate Method

2 getDate Method

Page 113: What is JScript?

getDay MethodReturns the day of the week value in a Date object using local time.

dateObj.getDay()

The required dateObj reference is a Date object.

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 weekand corresponds to a day of the week as follows:

Value Day of the Week0 Sunday1 Monday2 Tuesday3 Wednesday4 Thursday5 Friday6 SaturdayThe following example illustrates the use of the getDay method.

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

Date Object Methods | getUTCDay Method

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

getDay Method 1

Page 114: What is JScript?

2 getDay Method

2 getDay Method

Page 115: What is JScript?

getHours MethodReturns the hours value in a Date object using local time.

dateObj.getHours()

The required dateObj reference is a Date object.

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. Azero occurs in two situations: the time is before 1:00:00 am, or the time was not stored in the Date objectwhen the object was created. The only way to determine which situation you have is to also check the minutesand seconds for zero values. If they are all zeroes, it is nearly certain that the time was not stored in the Dateobject.

The following example illustrates the use of the getHours method.

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

Date Object Methods | getUTCHours Method | setHours Method | setUTCHours Method

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

getHours Method 1

Page 116: What is JScript?

2 getHours Method

2 getHours Method

Page 117: What is JScript?

getMinutes MethodReturns the minutes value in a Date object using local time.

dateObj.getMinutes()

The required dateObj reference is a Date object.

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 Dateobject. A zero is returned in two situations: when the time is less than one minute after the hour, or when thetime was not stored in the Date object when the object was created. The only way to determine whichsituation you have is to also check the hours and seconds for zero values. If they are all zeroes, it is nearlycertain that the time was not stored in the Date object.

Example

The following example illustrates the use of the getMinutes method.

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

Date Object Methods | getUTCMinutes Method | setMinutes Method | setUTCMinutes Method

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

getMinutes Method 1

Page 118: What is JScript?

2 getMinutes Method

2 getMinutes Method

Page 119: What is JScript?

getMonth MethodReturns the month value in the Date object using local time.

dateObj.getMonth()

The required dateObj reference is a Date object.

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. Theinteger returned is not the traditional number used to indicate the month. It is one less. If "Jan 5, 199608:47:00" is stored in a Date object, getMonth returns 0.

Example

The following example illustrates the use of the getMonth method.

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

Date Object Methods | getUTCMonth Method | setMonth Method | setUTCMonth Method

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

getMonth Method 1

Page 120: What is JScript?

2 getMonth Method

2 getMonth Method

Page 121: What is JScript?

getSeconds MethodReturns the seconds value in a Date object using local time.

dateObj.getSeconds()

The required dateObj reference is a Date object.

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 indicatedDate object. A zero is returned in two situations. One occurs when the time is less than one second into thecurrent 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. Ifthey are all zeroes, it is nearly certain that the time was not stored in the Date object.

Example

The following example illustrates the use of the getSeconds method.

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

Date Object Methods | getUTCSeconds Method | setSeconds Method | setUTCSeconds Method

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

getSeconds Method 1

Page 122: What is JScript?

2 getSeconds Method

2 getSeconds Method

Page 123: What is JScript?

getTime MethodReturns the time value in a Date object.

dateObj.getTime()

The required dateObj reference is a Date object.

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 yearsfrom 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 numberof milliseconds in a day, hour, or minute. For example:

var MinMilli = 1000 * 60var HrMilli = MinMilli * 60var DyMilli = HrMilli * 24

Example

The following example illustrates the use of the getTime method.

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

Date Object Methods | setTime Method

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

getTime Method 1

Page 124: What is JScript?

2 getTime Method

2 getTime Method

Page 125: What is JScript?

getTimezoneOffset MethodReturns the difference in minutes between the time on the host computer and Universal Coordinated Time(UTC).

dateObj.getTimezoneOffset()

The required dateObj reference is a Date object.

Remarks

The getTimezoneOffset method returns an integer value representing the number of minutes between thetime 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 clientscript, 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 areahead 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

The following example illustrates the use of the getTimezoneOffset method.

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

Date Object Methods

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

getTimezoneOffset Method 1

Page 126: What is JScript?

2 getTimezoneOffset Method

2 getTimezoneOffset Method

Page 127: What is JScript?

getVarDate MethodReturns the VT_DATE value in a Date object.

dateObj.getVarDate()

The required dateObj reference is a Date object.

Remarks

The getVarDate method is used when interacting with COM objects, ActiveX® objects or other objects thataccept and return date values in VT_DATE format, such as Visual Basic and VBScript. The actual format isdependent on regional settings and should not be replied upon within JScript.

Requirements

Version 3

See Also

getDate Method | parse Method

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

getVarDate Method 1

Page 128: What is JScript?

2 getVarDate Method

2 getVarDate Method

Page 129: What is JScript?

getYear MethodReturns the year value in a Date object.

dateObj.getYear()

The required dateObj reference is a Date object.

Remarks

This method is obsolete, and is provided for backwards compatibility only. Use the getFullYear methodinstead.

For the years 1900 though 1999, the year is a 2-digit integer value returned as the difference between thestored year and 1900. For dates outside that period, the 4-digit year is returned. For example, 1996 is returnedas 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 of1900 from the year value in the provided Date object, regardless of the value of the year. Forexample, the year 1899 is returned as -1 and the year 2000 is returned as 100.

Example

The following example illustrates the use of the getYear method:

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

Date Object Methods | getFullYear Method | getUTCFullYear Method | setFullYear Method |setUTCFullYear Method | setYear Method

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

getYear Method 1

Page 130: What is JScript?

2 getYear Method

2 getYear Method

Page 131: What is JScript?

indexOf MethodReturns the character position where the first occurrence of a substring occurs within a String object.

strObj.indexOf(subString[, startIndex])

Arguments

strObjRequired. A String object or literal.

subStringRequired. Substring to search for within the String object.

startIndexOptional. 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 Stringobject. 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, itis treated as the largest possible index.

Searching is performed from left to right. Otherwise, this method is identical to lastIndexOf.

Example

The following example illustrates the use of the indexOf method.

function IndexDemo(str2){ var str1 = "BABEBIBOBUBABEBIBOBU" var s = str1.indexOf(str2); return(s);}

Requirements

Version 1

See Also

lastIndexOf Method | String Object Methods | String Object Properties

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

indexOf Method 1

Page 132: What is JScript?

2 indexOf Method

2 indexOf Method

Page 133: What is JScript?

italics MethodPlaces HTML <I> tags around text in a String object.

strVariable.italics( )"String Literal".italics( )

Remarks

The following example demonstrates how the italics method works:

var strVariable = "This is a string";strVariable = strVariable.italics( );

The value of strVariable after the last statement is:

<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

bold Method | String Object Methods | String Object Properties

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

italics Method 1

Page 134: What is JScript?

2 italics Method

2 italics Method

Page 135: What is JScript?

item MethodReturns the current item in the collection.

enumObj.item()

The required enumObj reference is any Enumerator object.

Remarks

The item method returns the current item. If the collection is empty or the current item is undefined, it returnsundefined.

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

atEnd Method | moveFirst Method | moveNext Method

Applies To: Enumerator Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

item Method 1

Page 136: What is JScript?

2 item Method

2 item Method

Page 137: What is JScript?

join MethodReturns a string value consisting of all the elements of an array concatenated together and separated by thespecified separator character.

arrayObj.join(separator)

Arguments

arrayObjRequired. An Array object.

separatorRequired. A String object used to separate one element of an array from the next in the resultingString object. If omitted, the array elements are separated with a comma.

Remarks

If any element of the array is undefined or null, it is treated as an empty string.

Example

The following example illustrates the use of the join method.

function JoinDemo(){ var a, b; a = new Array(0,1,2,3,4); b = a.join("-"); return(b);}

Requirements

Version 2

See Also

Array Object Methods | String Object

Applies To: Array Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

join Method 1

Page 138: What is JScript?

2 join Method

2 join Method

Page 139: What is JScript?

lastIndexOf MethodReturns the last occurrence of a substring within a String object.

strObj.lastIndexOf(substring[, startindex])

Arguments

strObjRequired. A String object or literal.

substringRequired. The substring to search for within the String object.

startindexOptional. 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 Stringobject. 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, itis treated as the largest possible index.

Searching is performed right to left. Otherwise, this method is identical to indexOf.

The following example illustrates the use of the lastIndexOf method.

function lastIndexDemo(str2){ var str1 = "BABEBIBOBUBABEBIBOBU" var s = str1.lastIndexOf(str2); return(s);}

Requirements

Version 1

See Also

indexOf Method | String Object Methods | String Object Properties

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

lastIndexOf Method 1

Page 140: What is JScript?

2 lastIndexOf Method

2 lastIndexOf Method

Page 141: What is JScript?

lbound MethodReturns the lowest index value used in the specified dimension of a VBArray.

safeArray.lbound(dimension)

Arguments

safeArrayRequired. A VBArray object.

dimensionOptional. 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 ofdimensions 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 safearray. The second part is JScript code that determines the number of dimensions in the safe array and thelower bound of each dimension. Since the safe array is created in VBScript rather than Visual Basic, the lowerbound will always be zero. Both of these parts go into the <HEAD> section of an HTML page. The third partis 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 = aEnd 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

Page 142: What is JScript?

</HEAD>

<BODY><SCRIPT language="jscript"> document.write(VBArrayTest(CreateVBArray()));</SCRIPT></BODY>

Requirements

Version 3

See Also

dimensions Method | getItem Method | toArray Method | ubound Method

Applies To: VBArray Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 lbound Method

2 lbound Method

Page 143: What is JScript?

link MethodPlaces 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 themethod accomplishes this:

var strVariable = "This is a hyperlink";strVariable = strVariable.link("http://www.microsoft.com");

The value of strVariable after the last statement is:

<A HREF="http://www.microsoft.com">This is a hyperlink</A>

No checking is done to see if the tag has already been applied to the string.

Requirements

Version 1

See Also

anchor Method | String Object Methods | String Object Properties

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

link Method 1

Page 144: What is JScript?

2 link Method

2 link Method

Page 145: What is JScript?

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

The return value is the natural logarithm of number. The base is e.

Requirements

Version 1

See Also

Math Object Methods

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

log Method 1

Page 146: What is JScript?

2 log Method

2 log Method

Page 147: What is JScript?

match MethodExecutes a search on a string using a regular expression pattern, and returns an array containing the results ofthat search.

stringObj.match(rgExp)

Arguments

stringObjRequired. The String object or string literal on which to perform the search.

rgExpRequired. An instance of a Regular Expression object containing the regular expression pattern andapplicable flags. Can also be a variable name or string literal containing the regular expression patternand flags.

Remarks

If the match method does not find a match, it returns null. If it finds a match, match returns an array, and theproperties 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 propertycontains the entire searched string. The index property contains the position of the matched substring withinthe complete searched string. The lastIndex property contains the position following the last character in thelast match.

If the global flag (g) is not set, Element zero of the array contains the entire match, while elements 1 � ncontain any submatches that have occurred within the match. This behavior is identical to the behavior of theexec method without the global flag set. If the global flag is set, elements 0 - n contain all matches thatoccurred.

Example

The following example illustrates the use of the match method.

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

Page 148: What is JScript?

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

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 match Method

2 match Method

Page 149: What is JScript?

max MethodReturns the greater of zero or more supplied numeric expressions.

Math.max([number1[, number2[. . . [, numberN]]]])

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

Math Object Methods | min Method| NEGATIVE_INFINITY Property

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

max Method 1

Page 150: What is JScript?

2 max Method

2 max Method

Page 151: What is JScript?

min MethodReturns the lesser of zero or more supplied numeric expressions.

Math.min([number1[, number2[. . . [,numberN]]]])

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

Math Object Methods | max Method | POSITIVE_INFINITY Property

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

min Method 1

Page 152: What is JScript?

2 min Method

2 min Method

Page 153: What is JScript?

parse MethodParses 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 shownin the following example, rather than invoked as a method of a created Date object.

var datestring = "November 1, 1997 10:15 AM";Date.parse(datestring)

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, forexample "7/20/96".

Long dates of the form "July 10 1995" can be given with the year, month, and day in any order, andthe year in 2-digit or 4-digit form. If you use the 2-digit form, the year must be greater than or equalto 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 areresolved 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. Forexample, "Tuesday November 9 1996" is accepted and parsed even though that date actually falls on aFriday. The resulting Date object contains "Friday November 9 1996".

JScript handles all standard time zones, as well as Universal Coordinated Time (UTC) and GreenwichMean 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 twomonths is an error.

Example

The following example illustrates the use of the parse method. Provide the function with a date and thefunction 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

Page 154: What is JScript?

s += Math.round(Math.abs(t / DyMilli)) + " days " s += "between " + testdate + " and 1/1/70"; return(s); //Return results.}

Requirements

Version 1

See Also

Date Object Methods

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 parse Method

2 parse Method

Page 155: What is JScript?

parseFloat MethodReturns a floating-point number converted from a string.

parseFloat(numString)

The required numString argument is a string that contains a floating-point number.

Remarks

The parseFloat method returns a numerical value equal to the number contained in numString. If no prefix ofnumString can be successfully parsed into a floating-point number, NaN (not a number) is returned.

parseFloat("abc") // Returns NaN.parseFloat("1.2abc") // Returns 1.2.

You can test for NaN using the isNaN method.

Requirements

Version 1

See Also

isNaN Method | parseInt Method | String Object

Applies To: Global Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

parseFloat Method 1

Page 156: What is JScript?

2 parseFloat Method

2 parseFloat Method

Page 157: What is JScript?

parseInt MethodReturns an integer converted from a string.

parseInt(numString, [radix])

Arguments

numStringRequired. A string to convert into a number.

radixOptional. A value between 2 and 36 indicating the base of the number contained in numString. If notsupplied, strings with a prefix of '0x' are considered hexadecimal and strings with a prefix of '0' areconsidered 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 ofnumString can be successfully parsed into an integer, NaN (not a number) is returned.

parseInt("abc") // Returns NaN.parseInt("12abc") // Returns 12.

You can test for NaN using the isNaN method.

Requirements

Version 1

See Also

isNaN Method | parseFloat Method | String Object | valueOf Method

Applies To: Global Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

parseInt Method 1

Page 158: What is JScript?

2 parseInt Method

2 parseInt Method

Page 159: What is JScript?

pow MethodReturns the value of a base expression taken to a specified power.

Math.pow(base, exponent)

Arguments

baseRequired. The base value of the expression.

exponentRequired. The exponent value of the expression.

Example

In the following example, a numeric expression equal to baseexponent returns 1000.

Math.pow(10,3);

Requirements

Version 1

See Also

Math Object Methods

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

pow Method 1

Page 160: What is JScript?

2 pow Method

2 pow Method

Page 161: What is JScript?

random MethodReturns 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 canbe zero, but it will always be less than one. The random number generator is seeded automatically whenJScript is first loaded.

Requirements

Version 1

See Also

Math Object Methods

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

random Method 1

Page 162: What is JScript?

2 random Method

2 random Method

Page 163: What is JScript?

replace MethodReturns a copy of a string with text replaced using a regular expression or search string.

stringObj.replace(rgExp, replaceText)

Arguments

stringObjRequired. The String object or string literal on which to perform the replacement. This string is notmodified by the replace method.

rgExpRequired. An instance of a Regular Expression object containing the regular expression pattern andapplicable flags. Can also be a String object or literal. If rgExp is not an instance of a RegularExpression object, it is converted to a string, and an exact search is made for the results; no attempt ismade to convert the string into a regular expression.

replaceTextRequired. A String object or string literal containing the text to replace for every successful match ofrgExp in stringObj. In JScript 5.5 or later, the replaceText argument can also be a function that returnsthe 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 whichit came. The match variables can be used in text replacement where the replacement string has to bedetermined 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 + 3arguments where m is the number of left capturing parentheses in the rgExp. The first argument is thesubstring that matched. The next m arguments are all of the captures that resulted from the search. Argumentm + 2 is the offset within stringObj where the match occurred, and argument m + 3 is stringObj. The result isthe string value that results from replacing each matched substring with the corresponding return value of thefunction call.

The replace method updates the properties of the global RegExp object.

replace Method 1

Page 164: What is JScript?

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

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 replace Method

2 replace Method

Page 165: What is JScript?

reverse MethodReturns an Array object with the elements reversed.

arrayObj.reverse( )

The required arrayObj reference is an Array object.

Remarks

The reverse method reverses the elements of an Array object in place. It does not create a new Array objectduring 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

The following example illustrates the use of the reverse method.

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

Array Object Methods

Applies To: Array Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

reverse Method 1

Page 166: What is JScript?

2 reverse Method

2 reverse Method

Page 167: What is JScript?

round MethodReturns 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 thannumber. Otherwise, round returns the largest integer less than or equal to number.

Requirements

Version 1

See Also

Math Object Methods

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

round Method 1

Page 168: What is JScript?

2 round Method

2 round Method

Page 169: What is JScript?

search MethodReturns the position of the first substring match in a regular expression search.

stringObj.search(rgExp)

Arguments

stringObjRequired. The String object or string literal on which to perform the search.

rgExpRequired. An instance of a Regular Expression object containing the regular expression pattern andapplicable flags.

Remarks

The search method indicates if a match is present or not. If a match is found, the search method returns aninteger value that indicates the offset from the beginning of the string where the match occurred. If no matchis found, it returns -1.

Example

The following example illustrates the use of the search method.

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

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

search Method 1

Page 170: What is JScript?

2 search Method

2 search Method

Page 171: What is JScript?

setDate MethodSets the numeric date of the Date object using local time.

dateObj.setDate(numDate)

Arguments

dateObjRequired. Any Date object.

numDateRequired. 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 anegative number, the date is set to a date equal to numDate minus the number of days in the stored month. Forexample, 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

The following example illustrates the use of the setDate method.

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

Date Object Methods | getDate Method | getUTCDate Method | setUTCDate Method

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

setDate Method 1

Page 172: What is JScript?

2 setDate Method

2 setDate Method

Page 173: What is JScript?

setHours MethodSets the hour value in the Date object using local time.

dateObj.setHours(numHours[, numMin[, numSec[, numMilli]]])

Arguments

dateObjRequired. Any Date object.

numHoursRequired. A numeric value equal to the hours value.

numMinOptional. A numeric value equal to the minutes value. Must be supplied if either of the followingarguments is used.

numSecOptional. A numeric value equal to the seconds value. Must be supplied if the following argument isused.

numMilliOptional. 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 donot 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 modifiedaccordingly. For example, if the stored date is "Jan 5, 1996 00:00:00", and setHours(30) is called, the date ischanged to "Jan 6, 1996 06:00:00." Negative numbers have a similar behavior.

Example

The following example illustrates the use of the setHours method.

function SetHoursDemo(nhr, nmin, nsec){ var d, s; //Declare variables. d = new Date(); //Create Date object.

d.setHours(nhr, nmin, nsec); //Set hours, minutes, & seconds. s = "Current setting is " + d.toLocaleString() return(s); //Return new date setting.}

Requirements

Version 3

See Also

Date Object Methods | getHours Method | getUTCHours Method | setUTCHours Method

Applies To: Date Object

setHours Method 1

Page 174: What is JScript?

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 setHours Method

2 setHours Method

Page 175: What is JScript?

setMonth MethodSets the month value in the Date object using local time.

dateObj.setMonth(numMonth[, dateVal])

Arguments

dateObjRequired. Any Date object.

numMonthRequired. A numeric value equal to the month.

dateValOptional. A numeric value representing the date. If not supplied, the value from a call to the getDatemethod 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 ismodified accordingly. For example, if the stored date is "Jan 5, 1996" and setMonth(14) is called, the date ischanged to "Mar 5, 1997."

Example

The following example illustrates the use of the setMonth method.

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

Date Object Methods | getMonth Method | getUTCMonth Method | setUTCMonth Method

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

setMonth Method 1

Page 176: What is JScript?

2 setMonth Method

2 setMonth Method

Page 177: What is JScript?

setSeconds MethodSets the seconds value in the Date object using local time.

dateObj.setSeconds(numSeconds[, numMilli])

Arguments

dateObjRequired. Any Date object.

numSecondsRequired. A numeric value equal to the seconds value.

numMilliOptional. 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 donot specify an optional argument. For example, if the numMilli argument is optional, but not specified, JScriptuses 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 modifiedaccordingly. For example, if the stored date is "Jan 5, 1996 00:00:00" and setSeconds(150) is called, the dateis changed to "Jan 5, 1996 00:02:30."

Example

The following example illustrates the use of the setSeconds method.

function SetSecondsDemo(nsec, nmsec){ var d, s; //Declare variables. var sep = ":"; d = new Date(); //Create Date object.

d.setSeconds(nsec, nmsec); //Set seconds and milliseconds. s = "Current setting is "; s += d.toLocaleString() + sep + d.getMilliseconds(); return(s); //Return new setting.}

Requirements

Version 1

See Also

Date Object Methods | getSeconds Method | getUTCSeconds Method | setUTCSeconds Method

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

setSeconds Method 1

Page 178: What is JScript?

Build: Topic Version 5.6.9309.1546

JScript

2 setSeconds Method

2 setSeconds Method

Page 179: What is JScript?

setTime MethodSets the date and time value in the Date object.

dateObj.setTime(milliseconds)

Arguments

dateObjRequired. Any Date object.

millisecondsRequired. 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 approximately285,616 years from either side of 1970.

Setting the date and time with the setTime method is independent of the time zone.

Example

The following example illustrates the use of the setTime method.

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

Date Object Methods | getTime Method

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

setTime Method 1

Page 180: What is JScript?

2 setTime Method

2 setTime Method

Page 181: What is JScript?

setYear MethodSets the year value in the Date object.

dateObj.setYear(numYear)

Arguments

dateObjRequired. Any Date object.

numYearRequired. A numeric value equal to the year minus 1900.

Remarks

This method is obsolete, and is maintained for backwards compatibility only. Use the setFullYear methodinstead.

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 1900to the year value provided by numYear, regardless of the value of the year. For example, toset 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

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

setYear Method 1

Page 182: What is JScript?

2 setYear Method

2 setYear Method

Page 183: What is JScript?

sin MethodReturns the sine of a number.

Math.sin(number)

The number argument is a numeric expression for which the sine is needed.

Remarks

The return value is the sine of the numeric argument.

Requirements

Version 1

See Also

acos Method | asin Method | atan Method | cos Method | Math Object Methods | tan Method

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

sin Method 1

Page 184: What is JScript?

2 sin Method

2 sin Method

Page 185: What is JScript?

slice Method (Array)Returns a section of an array.

arrayObj.slice(start, [end])

Arguments

arrayObjRequired. An Array object.

startRequired. The index to the beginning of the specified portion of arrayObj.

endOptional. 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 treatedas length + start where length is the length of the array. If end is negative, it is treated as length + end wherelength is the length of the array. If end is omitted, extraction continues to the end of arrayObj. If end occursbefore 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:

newArray = myArray.slice(0, -1)

Requirements

Version 3

See Also

slice Method (String) | String Object

Applies To: Array Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

slice Method (Array) 1

Page 186: What is JScript?

2 slice Method (Array)

2 slice Method (Array)

Page 187: What is JScript?

slice Method (String)Returns a section of a string.

stringObj.slice(start, [end])

Arguments

stringObjRequired. A String object or literal.

startRequired. The index to the beginning of the specified portion of stringObj.

endOptional. 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 treatedas length + start where length is the length of the string. If end is negative, it is treated as length + end wherelength is the length of the string. If end is omitted, extraction continues to the end of stringObj. If end occursbefore 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

Array Object | slice Method (Array) | String Object Methods

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

slice Method (String) 1

Page 188: What is JScript?

2 slice Method (String)

2 slice Method (String)

Page 189: What is JScript?

small MethodPlaces HTML <SMALL> tags around text in a String object.

strVariable.small( )"String Literal".small( )

Remarks

The following example illustrates the use of the small method:

var strVariable = "This is a string";strVariable = strVariable.small( );

The value of strVariable after the last statement is:

<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

big Method | String Object Methods | String Object Properties

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

small Method 1

Page 190: What is JScript?

2 small Method

2 small Method

Page 191: What is JScript?

sort MethodReturns an Array object with the elements sorted.

arrayobj.sort(sortFunction)

Arguments

arrayObjRequired. Any Array object.

sortFunctionOptional. The name of the function used to determine the order of the elements. If omitted, theelements 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

The following example illustrates the use of the sort method.

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

Array Object Methods

Applies To: Array Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

sort Method 1

Page 192: What is JScript?

2 sort Method

2 sort Method

Page 193: What is JScript?

split MethodReturns the array of strings that results when a string is separated into substrings.

stringObj.split([separator[, limit]])

Arguments

stringObjRequired. The String object or literal to be split. This object is not modified by the split method.

separatorOptional. A string or an instance of a Regular Expression object identifying one or more charactersto use in separating the string. If omitted, a single-element array containing the entire string isreturned.

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

The following example illustrates the use of the split method.

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 ObjectMethods

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

split Method 1

Page 194: What is JScript?

2 split Method

2 split Method

Page 195: What is JScript?

sqrt MethodReturns the square root of a number.

Math.sqrt(number)

The required number argument is a numeric expression.

Remarks

If number is negative, the return value is NaN.

Requirements

Version 1

See Also

Math Object Methods | SQRT1_2 Property | SQRT2 Property

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

sqrt Method 1

Page 196: What is JScript?

2 sqrt Method

2 sqrt Method

Page 197: What is JScript?

strike MethodPlaces HTML <STRIKE> tags around text in a String object.

strVariable.strike( )"String Literal".strike( )

Remarks

The following example demonstrates how the strike method works:

var strVariable = "This is a string object";strVariable = strVariable.strike( );

The value of strVariable after the last statement is:

<STRIKE>This is a string object</STRIKE>

No checking is done to see if the tag has already been applied to the string.

Requirements

Version 1

See Also

String Object Methods | String Object Properties

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

strike Method 1

Page 198: What is JScript?

2 strike Method

2 strike Method

Page 199: What is JScript?

sub MethodPlaces HTML <SUB> tags around text in a String object.

strVariable.sub( )"String Literal".sub( )

Remarks

The following example demonstrates how the sub method works:

var strVariable = "This is a string object";strVariable = strVariable.sub( );

The value of strVariable after the last statement is:

<SUB>This is a string object</SUB>

No checking is done to see if the tag has already been applied to the string.

Requirements

Version 1

See Also

String Object Methods | String Object Properties | sup Method

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

sub Method 1

Page 200: What is JScript?

2 sub Method

2 sub Method

Page 201: What is JScript?

substr MethodReturns a substring beginning at a specified location and having a specified length.

stringvar.substr(start [, length ])

Arguments

stringvarRequired. A string literal or String object from which the substring is extracted.

startRequired. The starting position of the desired substring. The index of the first character in the string iszero.

lengthOptional. 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 ofstringvar.

Example

The following example illustrates the use of the substr method.

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

String Object Methods | String Object Properties | substring Method

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

substr Method 1

Page 202: What is JScript?

2 substr Method

2 substr Method

Page 203: What is JScript?

substring MethodReturns the substring at the specified location within a String object.

strVariable.substring(start, end)"String Literal".substring(start, end)

Arguments

startThe zero-based index integer indicating the beginning of the substring.

endThe 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. Forexample, strvar.substring(0, 3) and strvar.substring(3, 0) return the same substring.

If either start or end is NaN or negative, it is replaced with zero.

The length of the substring is equal to the absolute value of the difference between start and end. Forexample, the length of the substring returned in strvar.substring(0, 3) and strvar.substring(3, 0) is three.

Example

The following example illustrates the use of the substring method.

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

String Object Methods | String Object Properties | substr Method

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

substring Method 1

Page 204: What is JScript?

2 substring Method

2 substring Method

Page 205: What is JScript?

sup MethodPlaces HTML <SUP> tags around text in a String object.

strVariable.sup( )"String Literal".sup( )

Remarks

The following example demonstrates how the sup method works.

var strVariable = "This is a string object";strVariable = strVariable.sup( );

The value of strVariable after the last statement is:

<SUP>This is a string object</SUP>

No checking is done to see if the tag has already been applied to the string.

Requirements

Version 1

See Also

String Object Methods | String Object Properties | sub Method

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

sup Method 1

Page 206: What is JScript?

2 sup Method

2 sup Method

Page 207: What is JScript?

tan MethodReturns the tangent of a number.

Math.tan(number)

The required number argument is a numeric expression for which the tangent is sought.

Remarks

The return value is the tangent of number.

Requirements

Version 1

See Also

acos Method | asin Method | atan Method | atan2 Method | cos Method | Math Object Methods | sin Method

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

tan Method 1

Page 208: What is JScript?

2 tan Method

2 tan Method

Page 209: What is JScript?

test MethodReturns a Boolean value that indicates whether or not a pattern exists in a searched string.

rgExp.test(str)

Arguments

rgExpRequired. An instance of a Regular Expression object containing the regular expression pattern andapplicable flags.

strRequired. 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 regularexpression pattern and a string. The function will test for the occurrence of the regular expression pattern inthe string and return a string indicating the results of that search:

function TestDemo(re, s){ var s1; //Declare variable. // Test string for existence of regular expression. if (re.test(s)) //Test for existence. s1 = " contains "; //s contains pattern. else s1 = " does not contain "; //s does not contain pattern. return("'" + s + "'" + s1 + "'"+ re.source + "'"); //Return string.}

Requirements

Version 3

See Also

RegExp Object | Regular Expression Object | Regular Expression Object Methods | Regular ExpressionObject Properties | Regular Expression Syntax

Applies To: Regular Expression Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

test Method 1

Page 210: What is JScript?

2 test Method

2 test Method

Page 211: What is JScript?

toGMTString MethodReturns a date converted to a string using Greenwich Mean Time(GMT).

dateObj.toGMTString()

The required dateObj reference is any Date object.

Remarks

The toGMTString method is obsolete, and is provided for backwards compatibility only. It is recommendedthat 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

Date Object Methods | toUTCString Method

Applies To: Date Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

toGMTString Method 1

Page 212: What is JScript?

2 toGMTString Method

2 toGMTString Method

Page 213: What is JScript?

toLocaleString MethodReturns a date converted to a string using the current locale.

dateObj.toLocaleString()

The required dateObj is any Date object.

Remarks

The toLocaleString method returns a String object that contains the date written in the current locale's longdefault format.

For dates between 1601 and 1999 A.D., the date is formatted according to the user's Control PanelRegional 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, itreturns "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 usedas the basis for computation within a script as the returned result is machine-specific.

Example

The following example illustrates the use of the toLocaleString method.

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

Date Object Methods

Applies To: Array Object | Date Object | Number Object | Object Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

toLocaleString Method 1

Page 214: What is JScript?

2 toLocaleString Method

2 toLocaleString Method

Page 215: What is JScript?

toLowerCase MethodReturns a string where all alphabetic characters have been converted to lowercase.

strVariable.toLowerCase( )"String Literal".toLowerCase( )

Remarks

The toLowerCase method has no effect on nonalphabetic characters.

The following example demonstrates the effects of the toLowerCase method:

var strVariable = "This is a STRING object";strVariable = strVariable.toLowerCase( );

The value of strVariable after the last statement is:

this is a string object

Requirements

Version 1

See Also

String Object Methods | String Object Properties | toUpperCase Method

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

toLowerCase Method 1

Page 216: What is JScript?

2 toLowerCase Method

2 toLowerCase Method

Page 217: What is JScript?

toUpperCase MethodReturns a string where all alphabetic characters have been converted to uppercase.

strVariable.toUpperCase( )"String Literal".toUpperCase( )

Remarks

The toUpperCase method has no effect on non-alphabetic characters.

Example

The following example demonstrates the effects of the toUpperCase method:

var strVariable = "This is a STRING object";strVariable = strVariable.toUpperCase( );

The value of strVariable after the last statement is:

THIS IS A STRING OBJECT

Requirements

Version 1

See Also

String Object Methods | String Object Properties | toLowerCase Method

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

toUpperCase Method 1

Page 218: What is JScript?

2 toUpperCase Method

2 toUpperCase Method

Page 219: What is JScript?

ubound MethodReturns the highest index value used in the specified dimension of the VBArray.

safeArray.ubound(dimension)

Arguments

safeArrayRequired. A VBArray object.

dimensionOptional. 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 ofdimensions 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 safearray. The second part is JScript code that determines the number of dimensions in the safe array and theupper bound of each dimension. Both of these parts go into the <HEAD> section of an HTML page. The thirdpart 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 = aEnd 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

Page 220: What is JScript?

</HEAD>

<BODY><SCRIPT language="jscript"> document.write(VBArrayTest(CreateVBArray()));</SCRIPT></BODY>

Requirements

Version 3

See Also

dimensions Method | getItem Method | lbound Method | toArray Method

Applies To: VBArray Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 ubound Method

2 ubound Method

Page 221: What is JScript?

unescape MethodDecodes String objects encoded with the escape method.

unescape(charString)

The required charString argument is a String object or literal to be decoded.

Remarks

The unescape method returns a string value that contains the contents of charstring. All characters encodedwith 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 withhexadecimal 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

DecodeURI Method | decodeURIComponent Method | escape Method | String Object

Applies To: Global Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

unescape Method 1

Page 222: What is JScript?

2 unescape Method

2 unescape Method

Page 223: What is JScript?

Array ObjectProvides support for creation of arrays of any data type.

arrayObj = new Array()arrayObj = new Array([size])arrayObj = new Array([element0[, element1[, ...[, elementN]]]])

Arguments

arrayObjRequired. The variable name to which the Array object is assigned.

sizeOptional. The size of the array. As arrays are zero-based, created elements will have indexes fromzero to size -1.

element0,...,elementNOptional. The elements to place in the array. This creates an array with n + 1 elements, and a lengthof 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:

var my_array = new Array();for (i = 0; i < 10; i++) { my_array[i] = i; }x = my_array[4];

Since arrays in Microsoft JScript are zero-based, the last statement in the preceding example accesses the fifthelement 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 unsigned32-bit integer (< approximately four billion). That value then becomes the size of the array. If the value is anumber, 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, andthe 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

constructor Property | length Property | prototype Property

Methods

concat Method | join Method | pop Method | push Method | reverse Method | shift Method | slice Method | sortMethod | splice Method | toLocaleString Method | toString Method | unshift Method | valueOf Method

Array Object 1

Page 224: What is JScript?

Requirements

Version 2

See Also

new Operator

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 Array Object

2 Array Object

Page 225: What is JScript?

arguments ObjectAn object representing the arguments to the currently executing function, and the functions that called it.

[function.]arguments[n]

Arguments

functionOptional. The name of the currently executing Function object.

nRequired. 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 afunction begins execution. The arguments object of the function is not an array, but the individual argumentsare accessed the same way array elements are accessed. The index n is actually a reference to one of the 0�nproperties of the arguments object.

Example

The following example illustrates the use of the arguments object.

function ArgTest(a, b){ var i, s = "The ArgTest function expected "; var numargs = arguments.length; //Get number of arguments passed. var expargs = ArgTest.length; //Get number of arguments expected. if (expargs < 2) s += expargs + " argument. "; else s += expargs + " arguments. "; if (numargs < 2) s += numargs + " was passed."; else s += numargs + " were passed."; s += "\n\n" for (i =0 ; i < numargs; i++){ //Get argument contents. s += " Arg " + i + " = " + arguments[i] + "\n"; } return(s); //Return list of arguments.}

Requirements

Version 1

See Also

0�n Properties | callee Property | length Property

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

arguments Object 1

Page 226: What is JScript?

JScript

2 arguments Object

2 arguments Object

Page 227: What is JScript?

Date ObjectEnables basic storage and retrieval of dates and times.

dateObj = new Date()dateObj = new Date(dateVal)dateObj = new Date(year, month, date[, hours[, minutes[, seconds[,ms]]]])

Arguments

dateObjRequired. The variable name to which the Date object is assigned.

dateValRequired. If a numeric value, dateVal represents the number of milliseconds in Universal CoordinatedTime between the specified date and midnight January 1, 1970. If a string, dateVal is parsedaccording to the rules in the parse method. The dateVal argument can also be a VT_DATE value asreturned from some ActiveX® objects.

yearRequired. The full year, for example, 1976 (and not 76).

monthRequired. The month as an integer between 0 and 11 (January to December).

dateRequired. The date as an integer between 1 and 31.

hoursOptional. Must be supplied if minutes is supplied. An integer from 0 to 23 (midnight to 11pm) thatspecifies the hour.

minutesOptional. Must be supplied if seconds is supplied. An integer from 0 to 59 that specifies the minutes.

secondsOptional. Must be supplied if milliseconds is supplied. An integer from 0 to 59 that specifies theseconds.

msOptional. 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 valueof 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 theDate object, it is initialized to the current time (UTC). A value must be given to the object before you can useit.

The range of dates that can be represented in a Date object is approximately 285,616 years on either side ofJanuary 1, 1970.

The Date object has two static methods that are called without creating a Date object. They are parse andUTC.

Error

The following example illustrates the use of the Date object.

function DateDemo(){

Date Object 1

Page 228: What is JScript?

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

constructor Property | prototype Property

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 | toGMTStringMethod | toLocaleString Method | toUTCString Method | toString Method | valueOf Method | parse Method |UTC Method

Requirements

Version 1

See Also

new Operator | var Statement

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 Date Object

2 Date Object

Page 229: What is JScript?

Global ObjectAn 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 thescripting engine is initialized, thus making its methods and properties available immediately.

Properties

Infinity Property | NaN Property

Methods

escape Method | eval Method | isFinite Method | isNaN Method | parseFloat Method | parseInt Method |unescape Method

Requirements

Version 5

See Also

Object Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Global Object 1

Page 230: What is JScript?

2 Global Object

2 Global Object

Page 231: What is JScript?

Math ObjectAn intrinsic object that provides basic mathematics functionality and constants.

Math.[{property | method}]

Arguments

propertyRequired. Name of one of the properties of the Math. object.

methodRequired. 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. Thescripting engine creates it when the engine is loaded. All of its methods and properties are available to yourscript at all times.

Properties

E Property | LN2 Property | LN10 Property | LOG2E Property | LOG10E Property | PI Property | SQRT1_2Property | SQRT2 Property

Methods

abs Method | acos Method | asin Method | atan Method | atan2 Method | ceil Method | cos Method | expMethod | floor Method | log Method | max Method | min Method | pow Method | random Method | roundMethod | sin Method | sqrt Method | tan Method

Requirements

Version 1

See Also

Number Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Math Object 1

Page 232: What is JScript?

2 Math Object

2 Math Object

Page 233: What is JScript?

Regular Expression ObjectAn 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

reRequired. The variable name to which the regular expression pattern is assigned.

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

flagsOptional. Enclose flag in quotation marks if you use Syntax 2. Available flags, which may becombined, 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 theysound the same, they are separate and distinct. The properties of the Regular Expression object contain onlyinformation about one particular Regular Expression instance, while the properties of the global RegExpobject contain continually updated information about each match as it occurs.

Regular Expression objects store patterns used when searching strings for character combinations. After theRegular Expression object is created, it is either passed to a string method, or a string is passed to one of theregular expression methods. Information about the most recent search performed is stored in the globalRegExp object.

Use Syntax 1 when you know the search string ahead of time. Use Syntax 2 when the search string ischanging 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 thescript 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 RegularExpression 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.

Regular Expression Object 1

Page 234: What is JScript?

return(r); //Return results of match.}

Properties

lastIndex Property | source Property

Methods

compile Method | exec Method | test Method

Requirements

Version 3

See Also

RegExp Object | Regular Expression Syntax | String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 Regular Expression Object

2 Regular Expression Object

Page 235: What is JScript?

String ObjectAllows manipulation and formatting of text strings and determination and location of substrings withinstrings.

Syntax

newString = new String(["stringLiteral"])

Arguments

newStringRequired. The variable name to which the String object is assigned.

stringLiteralOptional. Any group of Unicode characters.

Remarks

String objects can be created implicitly using string literals. String objects created in this fashion (referred toas standard strings) are treated differently than String objects created using the new operator. All stringliterals share a common, global string object. If a property is added to a string literal, it is available to allstandard string objects:

var alpha, beta;alpha = "This is a string";beta = "This is also a string";

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:

var gamma, delta;gamma = new String("This is a string");delta = new String("This is also a string");

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 ofmembers. This is the only case where String objects and string literals are handled differently.

Properties

constructor Property | length Property | prototype Property

Methods

anchor Method | big Method | blink Method | bold Method | charAt Method | charCodeAt Method | concatMethod | fixed Method | fontcolor Method | fontsize Method | fromCharCode Method | indexOf Method |italics Method | lastIndexOf Method | link Method | match Method | replace Method | search Method | sliceMethod | small Method | split Method | strike Method | sub Method | substr Method | substring Method | supMethod | toLowerCase Method | toUpperCase Method | toString Method | valueOf Method

String Object 1

Page 236: What is JScript?

Requirements

Version 1

See Also

new Operator

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 String Object

2 String Object

Page 237: What is JScript?

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

resultAny variable.

expressionAny expression.

Remarks

Using this operator is exactly the same as specifying:

result = result + expression

The underlying subtype of the expressions determines the behavior of the += operator.

If ThenBoth expressions are numeric or Boolean AddBoth expressions are strings ConcatenateOne expression is numeric and the other is a string ConcatenateRequirements

Version 1

See Also

+ Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Addition Assignment Operator (+=) 1

Page 238: What is JScript?

2 Addition Assignment Operator (+=)

2 Addition Assignment Operator (+=)

Page 239: What is JScript?

Bitwise AND Assignment Operator (&=)Performs a bitwise AND on the value of a variable and the value of an expression and assigns the result to thevariable.

result &= expression

Arguments

resultAny variable.

expressionAny expression.

Remarks

Using this operator is exactly the same as specifying:

result = result & expression

The &= operator looks at the binary representation of the values of result and expression and does a bitwiseAND 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 a0 in that digit.

Requirements

Version 1

See Also

& Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Bitwise AND Assignment Operator (&=) 1

Page 240: What is JScript?

2 Bitwise AND Assignment Operator (&=)

2 Bitwise AND Assignment Operator (&=)

Page 241: What is JScript?

Bitwise AND Operator (&)Performs a bitwise AND on two expressions.

result = expression1 & expression2

Arguments

resultAny variable.

expression1Any expression.

expression2Any expression.

Remarks

The & operator looks at the binary representation of the values of two expressions and does a bitwise ANDoperation 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 a0 in that digit.

Requirements

Version 1

See Also

&= Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Bitwise AND Operator (&) 1

Page 242: What is JScript?

2 Bitwise AND Operator (&)

2 Bitwise AND Operator (&)

Page 243: What is JScript?

Bitwise Left Shift Operator (<<)Left shifts the bits of an expression.

result = expression1 << expression2

Arguments

resultAny variable.

expression1Any expression.

expression2Any expression.

Remarks

The << operator shifts the bits of expression1 left by the number of bits specified in expression2. Forexample:

var temptemp = 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

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Bitwise Left Shift Operator (<<) 1

Page 244: What is JScript?

2 Bitwise Left Shift Operator (<<)

2 Bitwise Left Shift Operator (<<)

Page 245: What is JScript?

Bitwise NOT Operator (~)Performs a bitwise NOT (negation) on an expression.

result = ~ expression

Arguments

resultAny variable.

expressionAny expression.

Remarks

All unary operators, such as the ~ operator, evaluate expressions as follows:

If applied to undefined or null expressions, a run-time error is raised.• Objects are converted to strings.• Strings are converted to numbers if possible. If not, a run-time error is raised.• Boolean values are treated as numbers (0 if false, 1 if true).•

The operator is applied to the resulting number.

The ~ operator looks at the binary representation of the values of the expression and does a bitwise negationoperation 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 expressionbecomes a 1 in the result.

Requirements

Version 1

See Also

! Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Bitwise NOT Operator (~) 1

Page 246: What is JScript?

2 Bitwise NOT Operator (~)

2 Bitwise NOT Operator (~)

Page 247: What is JScript?

Bitwise OR Assignment Operator (|=)Performs a bitwise OR on the value of a variable and the value of an expression and assigns the result to thevariable.

result |= expression

Arguments

resultAny variable.

expressionAny expression.

Remarks

Using this operator is exactly the same as specifying:

result = result | expression

The |= operator looks at the binary representation of the values of result and expression and does a bitwise ORoperation 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 a0 in that digit.

Requirements

Version 1

See Also

| Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Bitwise OR Assignment Operator (|=) 1

Page 248: What is JScript?

2 Bitwise OR Assignment Operator (|=)

2 Bitwise OR Assignment Operator (|=)

Page 249: What is JScript?

Bitwise OR Operator (|)Performs a bitwise OR on two expressions.

result = expression1 | expression2

Arguments

resultAny variable.

expression1Any expression.

expression2Any expression.

Remarks

The | operator looks at the binary representation of the values of two expressions and does a bitwise ORoperation 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 resultwill have a 0 in that digit.

Requirements

Version 1

See Also

|= Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Bitwise OR Operator (|) 1

Page 250: What is JScript?

2 Bitwise OR Operator (|)

2 Bitwise OR Operator (|)

Page 251: What is JScript?

Bitwise Right Shift Operator (>>)Right shifts the bits of an expression, maintaining sign.

result = expression1 >> expression2

Arguments

resultAny variable.

expression1Any expression.

expression2Any expression.

Remarks

The >> operator shifts the bits of expression1 right by the number of bits specified in expression2. The signbit 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 bitsequals -4 (11111100 in binary).

var temptemp = -14 >> 2

Requirements

Version 1

See Also

<< Operator | >>= Operator | >>> Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Bitwise Right Shift Operator (>>) 1

Page 252: What is JScript?

2 Bitwise Right Shift Operator (>>)

2 Bitwise Right Shift Operator (>>)

Page 253: What is JScript?

Bitwise XOR Assignment Operator (^=)Performs a bitwise exclusive OR on a variable and an expression and assigns the result to the variable.

result ^= expression

Arguments

resultAny variable.

expressionAny expression.

Remarks

Using the ^= operator is exactly the same as specifying:

result = result ^ expression

The ^= operator looks at the binary representation of the values of two expressions and does a bitwiseexclusive 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, theresult has a 0 in that digit.

Requirements

Version 1

See Also

^ Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Bitwise XOR Assignment Operator (^=) 1

Page 254: What is JScript?

2 Bitwise XOR Assignment Operator (^=)

2 Bitwise XOR Assignment Operator (^=)

Page 255: What is JScript?

Bitwise XOR Operator (^)Performs a bitwise exclusive OR on two expressions.

result = expression1 ^ expression2

Arguments

resultAny variable.

expression1Any expression.

expression2Any expression.

Remarks

The ^ operator looks at the binary representation of the values of two expressions and does a bitwiseexclusive 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, theresult has a 0 in that digit.

Requirements

Version 1

See Also

^= Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Bitwise XOR Operator (^) 1

Page 256: What is JScript?

2 Bitwise XOR Operator (^)

2 Bitwise XOR Operator (^)

Page 257: What is JScript?

Comma Operator (,)Causes two expressions to be executed sequentially.

expression1, expression2

Arguments

expression1Any expression.

expression2Any expression.

Remarks

The , operator causes the expressions on either side of it to be executed in left-to-right order, and obtains thevalue of the expression on the right. The most common use for the , operator is in the increment expression ofa for loop. For example:

for (i = 0; i < 10; i++, j++){ k = i + j;}

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

Requirements

Version 1

See Also

for Statement | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Comma Operator (,) 1

Page 258: What is JScript?

2 Comma Operator (,)

2 Comma Operator (,)

Page 259: What is JScript?

Comparison OperatorsReturns a Boolean value indicating the result of the comparison.

expression1 comparisonoperator expression2

Arguments

expression1Any expression.

comparisonoperatorAny comparison operator.

expression2Any 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 ofexpression1 and expression2:

Relational (<, >, <=, >=)

Attempt to convert both expression1 and expression2 into numbers.• If both expressions are strings, do a lexicographical string comparison.• If either expression is NaN, return false.• Negative zero equals Positive zero.• Negative Infinity is less than everything including itself.• Positive Infinity is greater than everything including itself.•

Equality (==, !=)

If the types of the two expressions are different, attempt to convert them to string, number, orBoolean.

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 sameobject, identical Boolean values, or (if different types) they can be coerced into one of thesesituations.

Every other comparison is considered unequal.•

Identity (===, !==)

These operators behave identically to the equality operators except no type conversion is done, and the typesmust be the same to be considered equal.

Requirements

Version 1

Comparison Operators 1

Page 260: What is JScript?

See Also

Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 Comparison Operators

2 Comparison Operators

Page 261: What is JScript?

Conditional (Ternary) Operator (?:)Executes one of two statements depending on a condition.

test ? statement1 : statement2

Arguments

testAny Boolean expression.

statement1A statement executed if test is true. May be a compound statement.

statement2A 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 wherean if...else statement would be awkward. For example:

var now = new Date();var greeting = "Good" + ((now.getHours() > 17) ? " evening." : " day.");

The example creates a string containing "Good evening." if it is after 6pm. The equivalent code using anif...else statement would look as follows:

var now = new Date();var greeting = "Good";if (now.getHours() > 17) greeting += " evening.";else greeting += " day.";

Requirements

Version 1

See Also

if...else Statement | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Conditional (Ternary) Operator (?:) 1

Page 262: What is JScript?

2 Conditional (Ternary) Operator (?:)

2 Conditional (Ternary) Operator (?:)

Page 263: What is JScript?

delete OperatorDeletes a property from an object, or removes an element from an array.

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 allowit to be deleted, false is returned.

In all other cases, true is returned.

Requirements

Version 3

See Also

Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

delete Operator 1

Page 264: What is JScript?

2 delete Operator

2 delete Operator

Page 265: What is JScript?

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

resultAny numeric variable.

expressionAny numeric expression.

Remarks

Using the /= operator is exactly the same as specifying:

result = result / expression

Requirements

Version 1

See Also

/ Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Division Assignment Operator (/=) 1

Page 266: What is JScript?

2 Division Assignment Operator (/=)

2 Division Assignment Operator (/=)

Page 267: What is JScript?

Increment (++) and Decrement ( � ) OperatorsIncrements or decrements the value of a variable by one.

Syntax 1

result = ++variableresult = --variableresult = variable++result = variable--

Syntax 2

++variable--variablevariable++variable--

Arguments

resultAny variable.

variableAny variable.

Remarks

The increment and decrement operators are used as a shortcut to modify the value stored in a variable. Thevalue of an expression containing one of these operators depends on whether the operator comes before orafter the variable:

var j, k;k = 2;j = ++k;

j is assigned the value 3, as the increment occurs before the expression is evaluated.

Contrast the following example:

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

Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Increment (++) and Decrement ( � ) Operators 1

Page 268: What is JScript?

Build: Topic Version 5.6.9309.1546

JScript

2 Increment (++) and Decrement ( � ) Operators

2 Increment (++) and Decrement ( � ) Operators

Page 269: What is JScript?

instanceof OperatorReturns a Boolean value that indicates whether or not an object is an instance of a particular class.

result = object instanceof class

Arguments

resultRequired. Any variable.

objectRequired. Any object expression.

classRequired. Any defined object class.

Remarks

The instanceof operator returns true if object is an instance of class. It returns false if object is not aninstance of the specified class, or if object is null.

Example

The following example illustrates the use of the instanceof operator.

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

var obj = new Date();response.write(objTest(obj));

Requirements

Version 5

See Also

Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

instanceof Operator 1

Page 270: What is JScript?

Build: Topic Version 5.6.9309.1546

JScript

2 instanceof Operator

2 instanceof Operator

Page 271: What is JScript?

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 theresult to the variable.

result <<= expression

Arguments

resultAny variable.

expressionAny expression.

Remarks

Using the <<= operator is exactly the same as specifying:

result = result << expression

The <<= operator shifts the bits of result left by the number of bits specified in expression. For example:

var temptemp = 14temp <<= 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

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Left Shift Assignment Operator (<<=) 1

Page 272: What is JScript?

2 Left Shift Assignment Operator (<<=)

2 Left Shift Assignment Operator (<<=)

Page 273: What is JScript?

Modulus Assignment Operator (%=)Divides the value of a variable by the value of an expression, and assigns the remainder to the variable.

result %= expression

Arguments

resultAny variable.

expressionAny numeric expression.

Remarks

Using the %= operator is exactly the same as specifying:

result = result % expression

Requirements

Version 1

See Also

% Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Modulus Assignment Operator (%=) 1

Page 274: What is JScript?

2 Modulus Assignment Operator (%=)

2 Modulus Assignment Operator (%=)

Page 275: What is JScript?

Modulus Operator (%)Divides the value of one expression by the value of another, and returns the remainder.

result = number1 % number2

Arguments

resultAny variable.

number1Any numeric expression.

number2Any numeric expression.

Remarks

The modulus, or remainder, operator divides number1 by number2 (rounding floating-point numbers tointegers) and returns only the remainder as result. For example, in the following expression, A (which isresult) equals 5.

A = 19 % 6.7

Requirements

Version 1

See Also

%= Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Modulus Operator (%) 1

Page 276: What is JScript?

2 Modulus Operator (%)

2 Modulus Operator (%)

Page 277: What is JScript?

Multiplication Assignment Operator (*=)Multiplies the value of a variable by the value of an expression and assigns the result to the variable.

result *= expression

Arguments

resultAny variable.

expressionAny expression.

Remarks

Using the *= operator is exactly the same as specifying:

result = result * expression

Requirements

Version 1

See Also

* Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Multiplication Assignment Operator (*=) 1

Page 278: What is JScript?

2 Multiplication Assignment Operator (*=)

2 Multiplication Assignment Operator (*=)

Page 279: What is JScript?

Multiplication Operator (*)Multiplies the value of two expressions.

result = number1*number2

Arguments

resultAny variable.

number1Any expression.

number2Any expression.

Requirements

Version 1

See Also

*= Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Multiplication Operator (*) 1

Page 280: What is JScript?

2 Multiplication Operator (*)

2 Multiplication Operator (*)

Page 281: What is JScript?

new OperatorCreates a new object.

new constructor[(arguments)]

Arguments

constructorRequired. Object's constructor. The parentheses can be omitted if the construc

tor takes no arguments.arguments

Optional. Any arguments to be passed to the new object's constructor.

Remarks

The new operator performs the following tasks:

It creates an object with no members.• It calls the constructor for that object, passing a pointer to the newly created object as the this pointer.• The constructor then initializes the object according to the arguments passed to the constructor.•

These are examples of valid uses of the new operator.

my_object = new Object;my_array = new Array();my_date = new Date("Jan 5 1996");

Requirements

Version 1

See Also

function Statement

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

new Operator 1

Page 282: What is JScript?

2 new Operator

2 new Operator

Page 283: What is JScript?

Right Shift Assignment Operator (>>=)Right shifts the value of a variable by the number of bits specified in the value of an expression, maintainingthe sign, and assigns the result to the variable.

result >>= expression

Arguments

resultAny variable.

expressionAny expression.

Remarks

Using the >>= operator is exactly the same as specifying:

result = result >> expression

The >>= operator shifts the bits of result right by the number of bits specified in expression. The sign bit ofresult is used to fill the digits from the left. Digits shifted off the right are discarded. For example, after thefollowing code is evaluated, temp has a value of -4: 14 (11110010 in binary) shifted right two bits equals -4(11111100 in binary).

var temptemp = -14temp >>= 2

Requirements

Version 1

See Also

<< Operator | >> Operator | >>> Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Right Shift Assignment Operator (>>=) 1

Page 284: What is JScript?

2 Right Shift Assignment Operator (>>=)

2 Right Shift Assignment Operator (>>=)

Page 285: What is JScript?

Subtraction Assignment Operator (-=)Subtracts the value of an expression from the value of a variable and assigns the result to the variable.

result -= expression

Arguments

resultAny numeric variable.

expressionAny numeric expression.

Remarks

Using the -= operator is exactly the same as doing the following:

result = result � expression

Requirements

Version 1

See Also

- Operator | Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Subtraction Assignment Operator (-=) 1

Page 286: What is JScript?

2 Subtraction Assignment Operator (-=)

2 Subtraction Assignment Operator (-=)

Page 287: What is JScript?

typeof OperatorReturns a string that identifies the data type of an expression.

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

The parentheses are optional in the typeof syntax.

Requirements

Version 1

See Also

Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

typeof Operator 1

Page 288: What is JScript?

2 typeof Operator

2 typeof Operator

Page 289: What is JScript?

Unsigned Right Shift Operator (>>>)Right shifts the bits of an expression, without maintaining sign.

result = expression1 >>> expression2

Arguments

resultAny variable.

expression1Any expression.

expression2Any expression.

Remarks

The >>> operator shifts the bits of expression1 right by the number of bits specified in expression2. Zeroesare filled in from the left. Digits shifted off the right are discarded. For example:

var temptemp = -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

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Unsigned Right Shift Operator (>>>) 1

Page 290: What is JScript?

2 Unsigned Right Shift Operator (>>>)

2 Unsigned Right Shift Operator (>>>)

Page 291: What is JScript?

Unsigned Right Shift Assignment Operator (>>>=)Right shifts the value of a variable by the number of bits specified in the value of an expression, withoutmaintaining sign, and assigns the result to the variable.

result >>>= expression

Arguments

resultAny variable.

expressionAny expression.

Remarks

Using the >>>= operator is exactly the same as doing the following:

result = result >>> expression

The >>>= operator shifts the bits of result right by the number of bits specified in expression. Zeroes arefilled in from the left. Digits shifted off the right are discarded. For example:

var temptemp = -14temp >>>= 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

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

Unsigned Right Shift Assignment Operator (>>>=) 1

Page 292: What is JScript?

2 Unsigned Right Shift Assignment Operator (>>>=)

2 Unsigned Right Shift Assignment Operator (>>>=)

Page 293: What is JScript?

void OperatorPrevents an expression from returning a value.

void expression

The expression argument is any valid JScript expression.

Remarks

The void operator evaluates its expression, and returns undefined. It is most useful in situations where youwant an expression evaluated but do not want the results visible to the remainder of the script.

Requirements

Version 2

See Also

Operator Precedence | Operator Summary

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

void Operator 1

Page 294: What is JScript?

2 void Operator

2 void Operator

Page 295: What is JScript?

0...n PropertiesReturns the actual value of individual arguments from an arguments object returned by the argumentsproperty of an executing function.

[function.]arguments[[0|1|2|...|n]]

Arguments

functionOptional. The name of the currently executing Function object.

0, 1, 2, �, nRequired. Non-negative integer in the range of 0 to n where 0 represents the first argument and nrepresents 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 notactually an array of arguments, the individual arguments that comprise the arguments object are accessed thesame way that array elements are accessed.

Example

The following example illustrates the use of the 0 . . . n properties of the arguments object. To fullyunderstand 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

Applies To: arguments Object | Function object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

0...n Properties 1

Page 296: What is JScript?

2 0...n Properties

2 0...n Properties

Page 297: What is JScript?

$1...$9 PropertiesReturns the nine most-recently memorized portions found during pattern matching. Read-only.

RegExp.$n

Arguments

RegExpAlways the global RegExp object.

n

Any integer from 1 through 9.

Remarks

The value of the $1...$9 properties is modified whenever a successful parenthesized match is made. Anynumber of parenthesized substrings may be specified in a regular expression pattern, but only the nine mostrecent can be stored.

The following example illustrates the use of the $1...$9 properties:

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

RegExp Object Properties | Regular Expression Syntax

Applies To: RegExp Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

$1...$9 Properties 1

Page 298: What is JScript?

2 $1...$9 Properties

2 $1...$9 Properties

Page 299: What is JScript?

callee PropertyReturns 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 associatedfunction is executing.

The initial value of the callee property is the Function object being executed. This allows anonymousfunctions 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

Applies To: arguments Object | Function object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

callee Property 1

Page 300: What is JScript?

2 callee Property

2 callee Property

Page 301: What is JScript?

constructor PropertySpecifies the function that creates an object.

object.constructor

The required object is the name of an object or function.

Remarks

The constructor property is a member of the prototype of every object that has a prototype. This includes allintrinsic JScript objects except the Global and Math objects. The constructor property contains a referenceto 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

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

constructor Property 1

Page 302: What is JScript?

2 constructor Property

2 constructor Property

Page 303: What is JScript?

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

exp Method | Math Object Properties

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

E Property 1

Page 304: What is JScript?

2 E Property

2 E Property

Page 305: What is JScript?

index PropertyReturns 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 asuccessful match is made.

Example

The following example illustrates the use of the index property. This function iterates a search string andprints 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

RegExp Object Properties | Regular Expression Syntax

Applies To: RegExp Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

index Property 1

Page 306: What is JScript?

2 index Property

2 index Property

Page 307: What is JScript?

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.

The following example illustrates the use of the input property:

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

RegExp Object Properties | Regular Expression Syntax

Applies To: RegExp Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

input Property ($_) 1

Page 308: What is JScript?

2 input Property ($_)

2 input Property ($_)

Page 309: What is JScript?

length Property (arguments)Returns the actual number of arguments passed to a function by the caller.

[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 ofarguments 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 understandthe example, pass more arguments to the function than the 2 arguments expected:

function ArgTest(a, b){ var i, s = "The ArgTest function expected "; var numargs = arguments.length; var expargs = ArgTest.length; if (expargs < 2) s += expargs + " argument. "; else s += expargs + " arguments. "; if (numargs < 2) s += numargs + " was passed."; else s += numargs + " were passed."; return(s);}

Requirements

Version 5.5

See Also

arguments Property | length Property (Array) | length Property (String)

Applies To: arguments Object | Function object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

length Property (arguments) 1

Page 310: What is JScript?

2 length Property (arguments)

2 length Property (arguments)

Page 311: What is JScript?

length Property (Array)Returns an integer value one higher than the highest element defined in an array.

numVar = arrayObj.length

Arguments

numVarRequired. Any numeric variable.

arrayObjRequired. Any Array object.

Remarks

As the elements in an array do not have to be contiguous, the length property is not necessarily the number ofelements in the array. For example, in the following array definition, my_array.length contains 7, not 2:

var my_array = new Array( );my_array[0] = "Test";my_array[6] = "Another Test";

If a value smaller than its previous value is assigned to the length property, the array is truncated, and anyelements 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 newelements created have the value undefined.

The following example illustrates the use of the length property:

function LengthDemo(){ var a; a = new Array(0,1,2,3,4); return(a.length);}

Requirements

Version 2

See Also

length Property (Function) | length Property (String)

Applies To: Array Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

length Property (Array) 1

Page 312: What is JScript?

2 length Property (Array)

2 length Property (Array)

Page 313: What is JScript?

length Property (Function)Returns the number of arguments defined for a function.

functionName.length

The required functionName is the name of the function.

Remarks

The length property of a function is initialized by the scripting engine to the number of arguments in thefunction'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 lengthproperty depends on the function.

The following example illustrates the use of the length property:

function ArgTest(a, b){ var i, s = "The ArgTest function expected "; var numargs = ArgTest.arguments.length; var expargs = ArgTest.length; if (expargs < 2) s += expargs + " argument. "; else s += expargs + " arguments. "; if (numargs < 2) s += numargs + " was passed."; else s += numargs + " were passed."; return(s);}

Requirements

Version 2

See Also

arguments Property | length Property (Array) | length Property (String)

Applies To: Function Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

length Property (Function) 1

Page 314: What is JScript?

2 length Property (Function)

2 length Property (Function)

Page 315: What is JScript?

length Property (String)Returns the length of a String object.

strVariable.length"String Literal".length

Remarks

The length property contains an integer that indicates the number of characters in the String object. The lastcharacter 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

Applies To: String Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

length Property (String) 1

Page 316: What is JScript?

2 length Property (String)

2 length Property (String)

Page 317: What is JScript?

LN10 PropertyReturns the natural logarithm of 10.

numVar = Math.LN10

Remarks

The LN10 property is approximately equal to 2.302.

Requirements

Version 1

See Also

Math Object Properties

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

LN10 Property 1

Page 318: What is JScript?

2 LN10 Property

2 LN10 Property

Page 319: What is JScript?

LN2 PropertyReturns the natural logarithm of 2.

numVar = Math.LN2

Syntax

The LN2 property is approximately equal to 0.693.

Requirements

Version 1

See Also

Math Object Properties

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

LN2 Property 1

Page 320: What is JScript?

2 LN2 Property

2 LN2 Property

Page 321: What is JScript?

LOG10E PropertyReturns the base-10 logarithm of e, Euler's constant.

varName = Math.LOG10E

Remarks

The LOG10E property, a constant, is approximately equal to 0.434.

Requirements

Version 1

See Also

Math Object Properties

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

LOG10E Property 1

Page 322: What is JScript?

2 LOG10E Property

2 LOG10E Property

Page 323: What is JScript?

LOG2E PropertyReturns the base-2 logarithm of e, Euler's constant.

varName = Math.LOG2E

Remarks

The LOG2E property, a constant, is approximately equal to 1.442.

Requirements

Version 1

See Also

Math Object Properties

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

LOG2E Property 1

Page 324: What is JScript?

2 LOG2E Property

2 LOG2E Property

Page 325: What is JScript?

PI PropertyReturns the ratio of the circumference of a circle to its diameter, approximately 3.141592653589793.

numVar = Math.PI

Syntax

The PI property, a constant, is approximately equal to 3.14159.

Requirements

Version 1

See Also

Math Object Properties

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

PI Property 1

Page 326: What is JScript?

2 PI Property

2 PI Property

Page 327: What is JScript?

prototype PropertyReturns a reference to the prototype for a class of objects.

objectName.prototype

The objectName argument is the name of an object.

Remarks

Use the prototype property to provide a base set of functionality to a class of objects. New instances of anobject "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 ofthe 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 theprototype, as in the example, but the object may not be assigned a different prototype. However, user-definedobjects may be assigned a new prototype.

The method and property lists for each intrinsic object in this language reference indicate which ones are partof 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

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

prototype Property 1

Page 328: What is JScript?

2 prototype Property

2 prototype Property

Page 329: What is JScript?

source PropertyReturns 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.

The following example illustrates the use of the source property:

function SourceDemo(re, s){ var s1; // Test string for existence of regular expression. if (re.test(s)) s1 = " contains "; else s1 = " does not contain "; // Get the text of the regular expression itself. return(s + s1 + re.source);}

Requirements

Version 3

See Also

Regular Expression Object Methods | Regular Expression Object Properties | Regular Expression Syntax

Applies To: Regular Expression Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

source Property 1

Page 330: What is JScript?

2 source Property

2 source Property

Page 331: What is JScript?

SQRT1_2 PropertyReturns he square root of 0.5, or one divided by the square root of 2.

numVar = Math.SQRT1_2

Remarks

The SQRT1_2 property, a constant, is approximately equal to 0.707.

Requirements

Version 1

See Also

Math Object Properties | sqrt Method | SQRT2 Property

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

SQRT1_2 Property 1

Page 332: What is JScript?

2 SQRT1_2 Property

2 SQRT1_2 Property

Page 333: What is JScript?

SQRT2 PropertyReturns the square root of 2.

numVar = Math.SQRT2

Syntax

The SQRT2 property, a constant, is approximately equal to 1.414.

Requirements

Version 1

See Also

Math Object Properties | sqrt Method | SQRT1_2 Property

Applies To: Math Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

SQRT2 Property 1

Page 334: What is JScript?

2 SQRT2 Property

2 SQRT2 Property

Page 335: What is JScript?

undefined PropertyReturns an initial value of undefined.

undefined

Remarks

The undefined property is a member of the Global object, and becomes available when the scripting engineis 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 thevariable to the string "undefined"

The undefined property is useful when explicitly testing or setting a variable to undefined.

Example

var declared; //Declare variable.if (declared == undefined) //Test variable. document.write("declared has not been given a value.");

if (typeOf(notDeclared) == "undefined") document.write("notDeclared has not been defined.");

Requirements

Version 5.5

See Also

Applies To: Global Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

undefined Property 1

Page 336: What is JScript?

2 undefined Property

2 undefined Property

Page 337: What is JScript?

@cc_on StatementActivates conditional compilation support.

@cc_on

Remarks

The @cc_on statement activates conditional compilation in the scripting engine.

It is strongly recommended that you use the @cc_on statement in a comment, so that browsers that do notsupport 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

Conditional Compilation | Conditional Compilation Variables | @if Statement | @set Statement

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

@cc_on Statement 1

Page 338: What is JScript?

2 @cc_on Statement

2 @cc_on Statement

Page 339: What is JScript?

@if StatementConditionally executes a group of statements, depending on the value of an expression.

@if (condition1

)text1

[@elif (condition2

)text2]

[@elsetext3]

@end

Arguments

condition1, condition2Optional. An expression that can be coerced into a Boolean expression.

text1Optional. Text to be parsed if condition1 is true.

text2Optional. Text to be parsed if condition1 is false and condition2 is true.

text3Optional. 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 usemultiple @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 textoutput. For example:

alert(@if (@_win32) "using Windows NT or Windows 95" @else "using Windows 3.1" @end)

Requirements

Version 3

See Also

Conditional Compilation | Conditional Compilation Variables | @cc_on Statement | @set Statement

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

@if Statement 1

Page 340: What is JScript?

2 @if Statement

2 @if Statement

Page 341: What is JScript?

@set StatementCreates variables used with conditional compilation statements.

@set @varname = term

Arguments

varnameRequired. Valid JScript variable name. Must be preceded by an "@" character at all times.

termRequired. Zero or more unary operators followed by a constant, conditional compilation variable, orparenthesized expression.

Remarks

Numeric and Boolean variables are supported for conditional compilation. Strings are not. Variables createdusing @set are generally used in conditional compilation statements, but can be used anywhere in JScriptcode.

Examples of variable declarations look like this:

@set @myvar1 = 12

@set @myvar2 = (@myvar1 * 20)

@set @myvar3 = @_jscript_version

The following operators are supported in parenthesized expressions:

! ~• * / %• + -• << >> >>>• < <= > >=• == != === !==• & ^ |• && | |•

If a variable is used before it has been defined, its value is NaN. NaN can be checked for using the @ifstatement:

@if (@newVar != @newVar) ...

This works because NaN is the only value not equal to itself.

Requirements

Version 3

See Also

Conditional Compilation | Conditional Compilation Variables | @cc_on Statement | @if Statement

@set Statement 1

Page 342: What is JScript?

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 @set Statement

2 @set Statement

Page 343: What is JScript?

break StatementTerminates 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. Youmost commonly use the label argument in switch statements, but it can be used in any statement, whethersimple or compound.

Executing the break statement exits from the current loop or statement, and begins script execution with thestatement immediately following.

Example

The following example illustrates the use of the break statement.

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

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

break Statement 1

Page 344: What is JScript?

2 break Statement

2 break Statement

Page 345: What is JScript?

Comment StatementsCauses 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@*/

The condStatement argument is conditional compilation code to be used if conditional compilation isactivated. If Syntax 3 is used, there can be no space between the "//" and "@" characters.

Remarks

Use comments to keep parts of a script from being read by the JScript parser. You can use comments toinclude 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 Syntax2 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 thatdo 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.

function myfunction(arg1, arg2){/* This is a multiline comment that

can span as many lines as necessary. */ var r;

// This is a single line comment. r = arg1 + arg2; // Sum the two arguments. return(r);}

Comment Statements 1

Page 346: What is JScript?

Requirements

Version 1

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 Comment Statements

2 Comment Statements

Page 347: What is JScript?

continue StatementStops 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 thecontinue statement stops the current iteration of the loop and continues program flow with the beginning ofthe 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

The following example illustrates the use of the continue statement.

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

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

continue Statement 1

Page 348: What is JScript?

2 continue Statement

2 continue Statement

Page 349: What is JScript?

do...while StatementExecutes a statement block once, and then repeats execution of the loop until a condition expression evaluatesto false.

do statementwhile (expression) ;

Arguments

statementOptional. The statement to be executed if expression is true. Can be a compound statement.

expressionOptional. An expression that can be coerced to Boolean true or false. If expression is true, the loop isexecuted 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 isexecuted 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

Page 350: What is JScript?

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 do...while Statement

2 do...while Statement

Page 351: What is JScript?

for StatementExecutes a block of statements for as long as a specified condition is true.

for (initialization; test; increment)statements

Arguments

initializationRequired. An expression. This expression is executed only once, before the loop is executed.

testRequired. A Boolean expression. If test is true, statement is executed. If test if false, the loop isterminated.

incrementRequired. An expression. The increment expression is executed at the end of every pass through theloop.

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

The following example demonstrates a for loop.

/* i is set to 0 at start, and is incremented by 1 at the end of each iteration. Loop terminates when i is not less than 10 before a loop iteration. */var myarray = new Array();for (i = 0; i < 10; i++) { myarray[i] = i;}

Requirements

Version 1

See Also

for...in Statement | while Statement

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

for Statement 1

Page 352: What is JScript?

2 for Statement

2 for Statement

Page 353: What is JScript?

for...in StatementExecutes one or more statements for each property of an object, or each element of an array.

for (variable in [object | array])statements

Arguments

variableRequired. A variable that can be any property of object or any element of an array.

object, arrayOptional. An object or array over which to iterate.

statementsOptional. 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 objector the element of array.

When iterating over an object, there is no way to determine or control the order in which the members of theobject 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] + "&ltBR>"; } return(s);}

Note Use the enumerator object to iterate members of a collection.

Requirements

Version 5

See Also

for Statement | while Statement

© 2001 Microsoft Corporation. All rights reserved.

for...in Statement 1

Page 354: What is JScript?

Build: Topic Version 5.6.9309.1546

JScript

2 for...in Statement

2 for...in Statement

Page 355: What is JScript?

function StatementDeclares a new function.

function functionname([arg1 [, arg2 [,...[, argN]]]]){

statements}

Arguments

functionnameRequired. The name of the function.

arg1...argNOptional. An optional, comma-separated list of arguments the function understands.

statementsOptional. One or more JScript statements.

Remarks

Use the function statement to declare a function for later use. The code contained in statements is notexecuted until the function is called from elsewhere in the script.

Example

The following example illustrates the use of the function statement.

function myfunction(arg1, arg2){ var r; r = arg1 * arg2; return(r);}

Note When calling a function, ensure that you always include the parentheses and anyrequired arguments. Calling a function without parentheses causes the text of the function tobe returned instead of the results of the function.

Requirements

Version 1

See Also

new Operator

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

function Statement 1

Page 356: What is JScript?

2 function Statement

2 function Statement

Page 357: What is JScript?

if...else StatementConditionally executes a group of statements, depending on the value of an expression.

if (condition)statement1

[elsestatement2]

Arguments

conditionRequired. A Boolean expression. If condition is null or undefined, condition is treated as false.

statement1Optional. The statement to be executed if condition is true. Can be a compound statement.

statement2Optional. 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 avoidinadvertent errors.

Example

In the following example, you may intend that the else be used with the first if statement, but it is used withthe second one.

if (x == 5)if (y == 6)

z = 17;else z = 20;

Changing the code in the following manner eliminates any ambiguities:

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 accidentallycreate 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 elsestatements. Braces are required around the statements between if and else.

if...else Statement 1

Page 358: What is JScript?

Requirements

Version 1

See Also

Conditional Operator (?:)

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 if...else Statement

2 if...else Statement

Page 359: What is JScript?

Labeled StatementProvides an identifier for a statement.

label :statements

Arguments

labelRequired. A unique identifier used when referring to the labeled statement.

statementsOptional. 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 andcontinue apply.

Example

In the following statement the continue statement uses a labeled statement to create an array in which thethird 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

break Statement | continue Statement

Labeled Statement 1

Page 360: What is JScript?

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 Labeled Statement

2 Labeled Statement

Page 361: What is JScript?

return StatementExits 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 doesnot return a value.

Remarks

You use the return statement to stop execution of a function and return the value of expression. If expressionis omitted, or no return statement is executed from within the function, the expression that called the currentfunction is assigned the value undefined.

Example

The following example illustrates the use of the return statement.

function myfunction(arg1, arg2){ var r; r = arg1 * arg2; return(r);}

Requirements

Version 1

See Also

function Statement

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

return Statement 1

Page 362: What is JScript?

2 return Statement

2 return Statement

Page 363: What is JScript?

switch StatementEnables the execution of one or more statements when a specified expression's value matches a label.

switch (expression) {case label :

statementlistcase label :

statementlist ...

default :statementlist

}

Arguments

expressionThe expression to be evaluated.

labelAn identifier to be matched against expression. If label === expression, execution starts with thestatementlist immediately after the colon, and continues until it encounters either a break statement,which is optional, or the end of the switch statement.

statementlistOne 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. Itcan 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 isnot supplied, no statements are executed.

Execution flows through a switch statement as follows:

Evaluate expression and look at label in order until a match is found.• If a label value equals expression, execute its accompanying statementlist.Continue execution until a break statement is encountered, or the switch statement ends. This meansthat multiple label blocks are executed if a break statement is not used.

If no label equals expression, go to the default case. If there is no default case, go to last step.• Continue execution at the statement following the end of the switch code block.•

Example

The following example tests an object for its type.

function MyObject() {...}

switch (object.constructor){case Date:

...case Number:

...case String:

...case MyObject:

...

switch Statement 1

Page 364: What is JScript?

default: ...}

Requirements

Version 3

See Also

break Statement | if...else Statement

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 switch Statement

2 switch Statement

Page 365: What is JScript?

this StatementRefers to the current object.

this.property

The required property argument is one of the current object's properties

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:

function Car(color, make, model){this.color = color;this.make = make;this.model = model;

}

For client versions of JScript, this refers to the window object if used outside of the context of any otherobject.

Requirements

Version 1

See Also

new Operator

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

this Statement 1

Page 366: What is JScript?

2 this Statement

2 this Statement

Page 367: What is JScript?

try...catch�finally StatementImplements error handling for JScript.

try {tryStatements}

catch(exception){catchStatements}

finally {finallyStatements}

Arguments

tryStatementsRequired. Statements where an error can occur.

exceptionRequired. Any variable name. The initial value of exception is the value of the thrown error.

catchStatementsOptional. Statements to handle errors occurring in the associated tryStatements.

finallyStatementsOptional. 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 occurin a given block of code, while still running code. If errors occur that the programmer has not handled, JScriptsimply 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 handleany error that does occur. If an error occurs in the tryStatements, program control is passed to catchStatementsfor processing. The initial value of exception is the value of the error that occurred in tryStatements. If noerror occurs, catchStatements are never executed.

If the error cannot be handled in the catchStatements associated with the tryStatements where the erroroccurred, 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 incatchStatements, the statements in finallyStatements are unconditionally executed.

Notice that the code inside finallyStatements is executed even if a return statement occurs inside the try orcatch blocks, or if the catch block re-throws the error. finallyStatments are guaranteed to always run, unlessan unhandled error occurs (for example, causing a run-time error inside the catch block).

Example

The following example shows how JScript exception handling works.

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

Page 368: What is JScript?

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

This produces the following output:

Outer try running..Nested try running...Nested catch caught an errorNested finally is running...Outer catch caught an error re-thrownOuter finally running

Requirements

Version 5

See Also

throw Statement

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

2 try...catch�finally Statement

2 try...catch�finally Statement

Page 369: What is JScript?

var StatementDeclares a variable.

var variable1 [ = value1 ] [, variable2 [ = value2], ...]

Arguments

variable1, variable2The names of the variables being declared.

value1, value2The initial value assigned to the variable.

Remarks

Use the var statement to declare variables. These variables can be assigned values at declaration or later inyour script.

Example

The following example illustrates the use of the var statement.

var index;var name = "Thomas Jefferson";var answer = 42, counter, numpages = 10;

Requirements

Version 1

See Also

function Statement | new Operator

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

var Statement 1

Page 370: What is JScript?

2 var Statement

2 var Statement

Page 371: What is JScript?

while StatementExecutes a statement until a specified condition is false.

while (expression)statements

Arguments

expressionRequired. A Boolean expression checked before each iteration of the loop. If expression is true, theloop is executed. If expression is false, the loop is terminated.

statementsOptional. 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, theloop is never executed.

Example

The following example illustrates the use of the while statement.

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

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

JScript

while Statement 1

Page 372: What is JScript?

2 while Statement

2 while Statement

Page 373: What is JScript?

with StatementEstablishes the default object for a statement.

with (object)statements

Arguments

objectThe new default object.

statementsOne 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 certainsituations. In the example that follows, notice the repeated use of Math.

x = Math.cos(3 * Math.PI) + Math.sin(Math.LN10) y = Math.tan(14 * Math.E)

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

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Visual Basic Scripting Edition

with Statement 1

Page 374: What is JScript?

2 with Statement

2 with Statement

Page 375: What is JScript?

VBScript User's GuideWhat Is VBScript?

Adding VBScript Code to an HTML Page

VBScript Fundamentals

VBScript Data Types

VBScript Variables

VBScript Constants

VBScript Operators

Using Conditional Statements

Looping Through Code

VBScript Procedures

VBScript Coding Conventions

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Visual Basic Scripting Edition

VBScript User's Guide 1

Page 376: What is JScript?

2 VBScript User's Guide

2 VBScript User's Guide

Page 377: What is JScript?

Adding VBScript Code to an HTML PageYou can use the SCRIPT element to add VBScript code to an HTML page.

The <SCRIPT> Tag

VBScript code is written within paired <SCRIPT> tags. For example, a procedure to test a delivery date mightappear as follows:

<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 scriptinglanguage. You must specify the language because browsers can use other scripting languages. Notice that theCanDeliver function is embedded in comment tags (<!� and �>). This prevents browsers that don'tunderstand 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 inthe 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 HEADsections. However, you will probably want to put all general-purpose scripting code in the HEAD section inorder to keep all the code together. Keeping your code in the HEAD section ensures that all code is read anddecoded 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 torespond to the events of objects in your form. For example, you can embed scripting code to respond to abutton 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>

Adding VBScript Code to an HTML Page 1

Page 378: What is JScript?

</BODY></HTML>

Most of your code will appear in either Sub or Function procedures and will be called only when specified byyour code. However, you can write VBScript code outside procedures, but still within a SCRIPT block. Thiscode is executed only once, when the HTML page loads. This allows you to initialize data or dynamicallychange the look of your Web page when it loads.

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Visual Basic Scripting Edition

2 Adding VBScript Code to an HTML Page

2 Adding VBScript Code to an HTML Page

Page 379: What is JScript?

A Simple VBScript PageA Simple Page

With Microsoft® Internet Explorer, you can view the page produced by the following HTML code. If youclick 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 VBScriptcode, and saves the code. When you click the button, Internet Explorer makes the connection between thebutton 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 Explorerlooks for and runs the corresponding event procedure, Button1_OnClick.

Internet Explorer defines the events available for form controls in the Internet Explorer Scripting ObjectModel 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 simpleinteractions between controls.

Other Ways to Attach Code to Events

Although the preceding way is probably the simplest and most general, you can attach VBScript code toevents in two other ways. Internet Explorer allows you to add short sections of inline code in the tag definingthe control. For example, the following <INPUT> tag performs the same action as the previous code examplewhen you click the button:

<INPUT NAME="Button1" TYPE="BUTTON" VALUE="Click Here" OnClick='MsgBox "Mirabile visu."'>

Notice that the function call itself is enclosed in single quotation marks, and the string for the MsgBoxfunction is enclosed in double quotation marks. You can use multiple statements as long as you separate thestatements with colons (:).

You can also write a <SCRIPT> tag so that it applies only to a particular event for a specific control:

A Simple VBScript Page 1

Page 380: What is JScript?

<SCRIPT LANGUAGE="VBScript" EVENT="OnClick" FOR="Button1"><!-- MsgBox "Mirabile visu."--></SCRIPT>

Because the <SCRIPT> tag already specifies the event and the control, you don't use Sub and End Substatements.

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Visual Basic Scripting Edition

2 A Simple VBScript Page

2 A Simple VBScript Page

Page 381: What is JScript?

VBScript and FormsSimple Validation

You can use Visual Basic Scripting Edition to do much of the form processing that you'd usually have to doon 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 useMicrosoft® Internet Explorer to view the page produced by the following code, you'll see a small text boxwith 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 IfEnd 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 propertyof the text box is used to check the entered value. To get the Value property, the code has to qualify thereference to the name of the text box.

You can always write out the full reference Document.ValidForm.Text1. However, where you havemultiple references to form controls, you'll want to do what was done here. First declare a variable. Then usethe 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.

Using Numeric Values

Notice that the example directly tests the value against a number: it uses the IsNumeric function to make surethe string in the text box is a number. Although VBScript automatically converts strings and numbers, it'salways a good practice to test a user-entered value for its data subtype and to use conversion functions asnecessary. When doing addition with text box values, convert the values explicitly to numbers because theplus sign (+) operator represents both addition and string concatenation. For example, if Text1 contains "1"and Text2 contains "2", you see the following results:

A = Text1.Value + Text2.Value ' A is "12"

VBScript and Forms 1

Page 382: What is JScript?

A = CDbl(Text1.Value) + Text2.Value ' A is 3

Validating and Passing Data Back to the Server

The simple validation example uses a plain button control. If a Submit control was used, the example wouldnever see the data to check it � everything would go immediately to the server. Avoiding the Submit controllets 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 IfEnd Sub--></SCRIPT>

To send the data to the server, the code invokes the Submit method on the form object when the data iscorrect. From there, the server handles the data just as it otherwise would � except that the data is correctbefore it gets there. Find complete information about the Submit method and other methods in the InternetExplorer 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 fullpower of ActiveX® controls (formerly called OLE controls) and Java objects.

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Visual Basic Scripting Edition

2 VBScript and Forms

2 VBScript and Forms

Page 383: What is JScript?

Using VBScript with ObjectsUsing Objects

Whether you use an ActiveX® control (formerly called an OLE control) or a Java object, Microsoft VisualBasic Scripting Edition and Microsoft® Internet Explorer handle it the same way. If you're using InternetExplorer 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. Ifyou're a Visual Basic programmer, you'll recognize that using the <PARAM> tags is just like setting initialproperties for a control on a form. For example, the following set of <OBJECT> and <PARAM> tags adds theActiveX 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. Thefollowing code, for example, includes <FORM> controls you can use to manipulate two properties of theLabel 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.ValueEnd 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 informationabout the properties, methods, and events there, as well as the class identifiers (CLSID) for the controls on theMicrosoft® Web site (http://www.microsoft.com). You can find more information about the <OBJECT> tagon the Internet Explorer 4.0 Author's Guide and HTML Reference page.

Using VBScript with Objects 1

Page 384: What is JScript?

Note Earlier releases of Internet Explorer required braces ({}) around the classid attributeand did not conform to the W3C specification. Using braces with the current release generatesa "This page uses an outdated version of the <OBJECT> tag" message.

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Visual Basic Scripting Edition

2 Using VBScript with Objects

2 Using VBScript with Objects

Page 385: What is JScript?

VBScript Language ReferenceConstants

Errors

Events

Functions

Methods

Miscellaneous

Objects and Collections

Operators

Properties

Statements

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Scripting Runtime Library

VBScript Language Reference 1

Page 386: What is JScript?

2 VBScript Language Reference

2 VBScript Language Reference

Page 387: What is JScript?

Count PropertyReturns the number of items in a collection or Dictionary object. Read-only.

object.Count

The object is always the name of one of the items in the Applies To list.

Remarks

The following code illustrates use of the Count property:

[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 = sEnd Function

See Also

CompareMode Property | Item Property | Key Property

Applies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Scripting Runtime Library

Count Property 1

Page 388: What is JScript?

2 Count Property

2 Count Property

Page 389: What is JScript?

Item PropertySets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on thespecified key. Read/write.

object.Item(key)[ = newitem]

Arguments

objectRequired. Always the name of a collection or Dictionary object.

keyRequired. Key associated with the item being retrieved or added.

newitemOptional. Used for Dictionary object only; no application for collections. If provided, newitem is thenew 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 foundwhen attempting to return an existing item, a new key is created and its corresponding item is left empty.

The following example illustrates the use of the Item property.

[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

CompareMode Property | Count Property | Key Property

Applies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Item Property 1

Page 390: What is JScript?

Scripting Runtime Library

2 Item Property

2 Item Property

Page 391: What is JScript?

Key PropertySets a key in a Dictionary object.

object.Key(key) = newkey

Arguments

objectRequired. Always the name of a Dictionary object.

keyRequired. Key value being changed.

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

The following example illustrates the use of the Key property:

[JScript]var d;d = new ActiveXObject("Scripting.Dictionary");

function AddStuff(){ var a; d.Add("a", "Athens"); d.Add("b", "Belgrade"); d.Add("c", "Cairo");}

function ChangeKey(oldkey, newkey){ var s;

d.Key("c") = "Ca"; s = "Key " + oldkey + " changed to " + newkey; return(s);}[VBScript]Function DicDemo 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"

d.Key("c") = "d" ' Set key for "c" to "d". DicDemo = d.Item("d") ' Return associate item.End Function

See Also

CompareMode Property | Count Property | Item Property

Applies To: Dictionary Object

Key Property 1

Page 392: What is JScript?

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Scripting Runtime Library

2 Key Property

2 Key Property

Page 393: What is JScript?

Add Method (Dictionary)Adds a key and item pair to a Dictionary object.

object.Add (key, item)

Arguments

objectRequired. Always the name of a Dictionary object.

keyRequired. The key associated with the item being added.

itemRequired. The item associated with the key being added.

Remarks

An error occurs if the key already exists.

The following example illustrates the use of the Add method.

[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

Applies To: Dictionary Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Scripting Runtime Library

Add Method (Dictionary) 1

Page 394: What is JScript?

2 Add Method (Dictionary)

2 Add Method (Dictionary)

Page 395: What is JScript?

Column PropertyRead-only property that returns the column number of the current character position in a TextStream file.

object.Column

The object is always the name of a TextStream object.

Remarks

After a newline character has been written, but before any other character is written, Column is equal to 1.

The following examples illustrates the use of the Column property:

[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.ColumnEnd Function

See Also

Line Property

Applies To: TextStream Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Scripting Runtime Library

Column Property 1

Page 396: What is JScript?

2 Column Property

2 Column Property

Page 397: What is JScript?

Line PropertyRead-only property that returns the current line number in a TextStream file.

object.Line

The object is always the name of a TextStream object.

Remarks

After a file is initially opened and before anything is written, Line is equal to 1.

The following example illustrates the use of the Line property:

[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.LineEnd Function

See Also

Column Property

Applies To: TextStream Object

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Scripting Runtime Library

Line Property 1

Page 398: What is JScript?

2 Line Property

2 Line Property

Page 399: What is JScript?

Add Method (Folders)Adds a new folder to a Folders collection.

object.Add (folderName)

Arguments

objectRequired. Always the name of a Folders collection.

folderNameRequired. 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 IfEnd Sub

An error occurs if the folderName already exists.

See Also

Add Method (Dictionary)Applies To: Folders Collection

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Scripting Runtime Library

Add Method (Folders) 1

Page 400: What is JScript?

2 Add Method (Folders)

2 Add Method (Folders)

Page 401: What is JScript?

Count PropertyReturns the number of items in a collection or Dictionary object. Read-only.

object.Count

The object is always the name of one of the items in the Applies To list.

Remarks

The following code illustrates use of the Count property:

[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 = sEnd Function

See Also

CompareMode Property | Item Property | Key Property

Applies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

Count Property 1

Page 402: What is JScript?

2 Count Property

2 Count Property

Page 403: What is JScript?

Script ComponentsMicrosoft® Windows® Script Components provide you with an easy way to create COM components usingscripting languages such as Microsoft® Visual Basic® Scripting Edition (VBScript) and Microsoft®JScript®. Use script components as COM components in applications such as Microsoft® InternetInformation Services (IIS), Microsoft® Windows® Script Host, and any other application that can supportCOM 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 functionalityof 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 inMicrosoft® Internet Explorer 5.0 to define behaviors.

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

Script Components 1

Page 404: What is JScript?

2 Script Components

2 Script Components

Page 405: What is JScript?

Script Components OverviewWindows® Script Components are an exciting new technology that allows you to create powerful, reusableCOM 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 componenttechnology, 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 howto create script components.

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

Script Components Overview 1

Page 406: What is JScript?

2 Script Components Overview

2 Script Components Overview

Page 407: What is JScript?

Introducing Windows Script ComponentsWindows® Script Components provide you with an easy way to create powerful, reusable COM componentsin script. You create script components using any scripting language that supports the Microsoft® ActiveX®Scripting interfaces. Script languages that support these interfaces include JScript, Microsoft® Visual Basic®Scripting Edition (VBScript), PERLScript, PScript, and Python.

Note For more information about ActiveX Scripting interfaces, see the Microsoft ScriptingTechnologies 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:

Are small and efficient.• Are easy to create, maintain, and deploy.• Provide the ability to create COM components.• Provide access to a broad range of system services.•

Using script components, you can create COM components for a variety of tasks, such as performingmiddle-tier business logic, accessing and manipulating database data, adding transaction processing toapplications, and adding interactive effects to a Web page using DHTML Behaviors.

See Also

How Script Components Work | Creating Script Components

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

Introducing Windows Script Components 1

Page 408: What is JScript?

2 Introducing Windows Script Components

2 Introducing Windows Script Components

Page 409: What is JScript?

How Script Components WorkWindows® Script Component technology consists of three pieces:

The script component run-time (Scrobj.dll), which helps dispatch COM requests to your scripts. InCOM 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, anASP interface handler, and a handler for DHTML Behaviors, are already built into the scriptcomponent run-time. Others are available as add-on components, or embedded into specificapplications.

Your script component file (an .wsc file). Script component files are XML (Extensible MarkupLanguage) files that contain information about what type of COM component you want to create (thatis, what interface handlers you want to use). Then, depending on what functionality the handler makesavailable, 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 variousinterface handlers. Your script component contains only the script required to implement the functionality ofthe COM component.

For example, one of the most common types of COM components is an Automation component, which is acomponent with properties and methods that can be called from other applications. The low-level COMinterfaces required to implement this functionality � such as dispatching to the correct function when amethod is called � are built into an Automation interface handler. In your script component file, you definethe properties, methods, and events you want to expose, and the Automation handler makes sure they arecalled correctly when the host application needs them.

See Also

Introducing Script Components | Creating Script Components

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

How Script Components Work 1

Page 410: What is JScript?

2 How Script Components Work

2 How Script Components Work

Page 411: What is JScript?

Script Component File ContentsWindows® Script Component files are XML (Extensible Markup Language) that are much like HTML files,but contain special elements that define the script component and its behavior. The elements used for definingscript components are not HTML tags, but are XML elements specifically used for script componentdefinitions.

A basic script component file contains these elements:

<component> and <package> elements The <component> element encloses one entire scriptcomponent definition. Multiple <component> elements can appear in the same .wsc file, and arecontained within a master <package> element.

<registration> element Includes information used to register your script component as a COMcomponent. This element might not be required if the host application (such as Microsoft® InternetExplorer 5.0) does not directly use the Windows registry when creating an instance of the scriptcomponent.

<public> element Encloses definitions for properties, methods, and events that your scriptcomponent 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, whichdetermines 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 theASP object model in your script component.

The <public> element is used to specify that a script component implements the COM Automationinterface handler. Therefore, you don't need to create an <implements> element for the Automationhandler.

Note The script component run-time includes interface handlers for Automation(exposed using the <public> element), for ASP, and for Internet Explorer 5.0DHTML Behaviors. Other interface handlers are available as external DLLs. Formore information about additional interface handlers and script components, see theMicrosoft 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 aCOM Automation component, you declare properties, methods, and events in a <public> element, andthen 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 anotherCOM 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 betranslated, 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 andexecuted.

Note If you are concerned that the .wsc files you create contain XML that conformsto XML standards, you can specify that the script component's XML parser check theXML syntax. For example, this is useful if you think you might someday use anXML editor to work with your files. Otherwise, however, it is not usually a concern.For more details, see Script Component Files and XML Conformance.

Script Component File Contents 1

Page 412: What is JScript?

Skeleton Script Component File

The following example illustrates how to construct a script component file.

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

<implements type=COMhandlerName id=internalName> (interface-specific definitions here) </implements>

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

<object id="objID" classid="clsid:00000000-0000-0000-000000000000"> <resource ID="resourceID1">string or number here</resource> <resource ID="resourceID2">string or number here</resource></component></package>

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:

2 Script Component File Contents

2 Script Component File Contents

Page 413: What is JScript?

The <?XML ?> declaration at the top indicates that this is an XML file and that it conforms to XMLprotocol. This declaration is optional; if you leave it out, you can use slightly looser syntax whencreating the script component's elements. For details, see Script Component Files and XMLConformance.

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 checkingoptions. For details, see Checking For Errors in Script Component Files. If you do not include thiselement, 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 thatimplements the DHTML Behaviors interface handler in Internet Explorer 5.0 does not need to beregistered, because Internet Explorer directly instantiates the behaviors as they are detected on thepage. For details about registration requirements, see the documentation for the interface handler youare 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 thelibrary's constants in your script.

The <public> element encloses <property>, <method>, and <event> elements. The script that definesthese appears later in the script component file.

The <implements> element is used to make available non-default COM interfaces. For example, youcan expose the ASP interface with an <implements> type such as the following:

<implements type="ASP" id="iASP">

The exact elements that appear inside an <implements> element depend on what interface you areimplementing.

Note The <implements> element is shown here with an id attribute. However, thisattribute is optional, except in cases where you must disambiguate objects orvariables. For details, see the <implements> element.

In this skeleton, there are two script elements, one for VBScript and one for JScript. If you are usingonly 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 scriptin 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 scriptcomponent.

After creating the skeleton, fill in the elements to define the script component's functionality, depending onwhich interface handler you are implementing.

See Also

Checking For Errors in Script Component Files | Creating a Script Component Type Library | CreatingRegistration Information | Exposing Events | Exposing Methods | Exposing Properties | Implementing ASPScript Components | Implementing DHTML Behavior Script Components | Script Component Files and XMLConformance | Using the Script Component Wizard

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

Script Component File Contents 3

Script Component File Contents 3

Page 414: What is JScript?

4 Script Component File Contents

4 Script Component File Contents

Page 415: What is JScript?

Using the Script Component WizardThe Windows® Script Component package includes a Script Component Wizard that automates the processof creating a script component (.wsc) file. The wizard performs the following functions:

Creates the .wsc file and adds basic XML elements.• Prompts for and creates registration information.• Prompts for the type of interface handler you want the script component to use.• Prompts for properties you want to expose and creates the necessary elements in the scriptinglanguage you specify.

Prompts for methods you want to expose and creates the necessary elements in the scripting languageyou specify.

Prompts for events that the script component can fire and creates the skeleton event elements.

Note You can download and install the Script Component Wizard from theMicrosoft 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 thetop, meaning that the contents of the file must be XML-conformant. For more details, seeScript Component Files and XML Conformance.

See Also

Script Component File Contents | Creating Registration Information | Creating Script Components | ScriptComponent Files and XML Conformance

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

Using the Script Component Wizard 1

Page 416: What is JScript?

2 Using the Script Component Wizard

2 Using the Script Component Wizard

Page 417: What is JScript?

Creating Registration InformationIf the host application requires it, you can register a Windows® Script Component as a COM componentusing a program such as Regsvr32.exe. Registration places information about the COM component in a publiclocation (in Windows, registration information is stored in the Windows registry). By reading the registrationinformation, applications can find and load the COM component.

Note Registration is not required in every case. For example, a script component thatimplements the DHTML Behaviors interface handler in Internet Explorer 5.0 does not need tobe registered, because Internet Explorer registers the behaviors as they are detected on thepage. For more details about using Behaviors, see the "Using DHTML Behaviors" topic onthe Microsoft Site Builder Network (SBN) Web site. If the host application supportsmonikers, you can also create an instance of a script component without registering it.

When you specify registration, the most important information is:

A program ID (prog ID), which is the name used in the host application when creating an instance ofthe script component. For example, if your script component's program ID isComponent.MyComponent, you can create an instance of it in Microsoft® Visual Basic® using astatement such as the following:

Set Component = CreateObject("Component.MyComponent")

A class ID, which is a GUID (globally unique ID) that uniquely identifies your script component. Youcan generate a GUID with a program such as Uuidgen.exe.

Note If you create a script component using the Script Component Wizard, thewizard automatically creates a program ID and class ID for you. For details, seeUsing The Script Component Wizard.

Registration information also includes a description and a version number.

The registration program can create a class ID for your script component when it is registered. However, it ishighly recommended that you provide a class ID for the script component yourself, to ensure that your scriptcomponent has the same class ID on all computers on which it is registered. Allowing the registration programto create a class ID can also cause problems if you use the script component with development tools that storeclass IDs. If the registration creates a new class ID each time, it will not match the ID stored by theapplication.

To create registration information for the script component

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:

<registrationdescription="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.

Creating Registration Information 1

Page 418: What is JScript?

Running Script During Registration

The script component <registration> element also allows you to include script that will be executed when thescript component is registered and unregistered. For example, you can post a message that the scriptcomponent has been registered.

To run script during registration and unregistration

In the <registration> element, include an <script> element. To run script during registration, write aregister( ) function. To run script when the script component has been unregistered, include anunregister( ) function.

The following example shows how to post messages when the script component is registered orunregistered.

Note A CDATA section is required to make the script in the <script> elementopaque. 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>

Registering for Remote Access

If you are deploying your script component in a distributed environment, you can specify that the scriptcomponent can be instantiated remotely. For example, you might be creating a script component designed torun on a server, but which will be called from code on a client. This scenario is possible if the client andserver machines are properly configured with DCOM, which provides the mechanism for passing objectpointers to the client from the server.

To register a script component for remote access

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

2 Creating Registration Information

2 Creating Registration Information

Page 419: What is JScript?

See Also

Script Component File Contents | Using The Script Component Wizard | Creating a Script Component TypeLibrary | Checking For Errors in Script Component Files | Script Component Files and XML Conformance

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

Creating Registration Information 3

Creating Registration Information 3

Page 420: What is JScript?

4 Creating Registration Information

4 Creating Registration Information

Page 421: What is JScript?

Exposing MethodsMethods are implemented as functions or subroutines in your Windows® Script Component file.

To expose a method

Create a <public> element as a child of the <component> element.1. In the <public> element, include a <method> element. The method element can optionally includeone or more <parameter> elements to define the method's parameters.

2.

Write a procedure in any scripting language to implement the function. Place the procedure in a<script> element outside the <implements> element but within the <component> element. Be sure thefunction name matches the functionName, or if you did not specify a functionName, the methodNamename you specified in the <method> element.

For example, the following example shows a fragment from a script component file with twomethods, factorial and getRandomNumber.

Note A CDATA section is required to make the script in the <script> elementopaque. 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 IfEnd Function

Function getRandomNumber(upperBound, seed) getRandomNumber = Cint(upperBound * Rnd(seed) + 1)End Function]]></script>

3.

You can specify a default method for a script component so the host application can invoke the methodwithout explicitly calling it. For example, if you have exposed a method called factorial and marked it as thedefault, you can call it in the followoing ways in Visual Basic:

Set component = CreateObject("component.MyComponent")n = component.factorial(4) ' Calls factorial method explicitly.n = component(4) ' Calls factorial method as default.

To specify a default method, include an attribute assigning a special dispatch identifier (a dispid) to themethod. For more information about dispids, see Exposing Events.

Exposing Methods 1

Page 422: What is JScript?

To specify a default method

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 defaultproperty, but not both. There can be only one element in the script component withthe dispid of zero.

See Also

Exposing Events | Exposing Properties | Script Component File Contents

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

2 Exposing Methods

2 Exposing Methods

Page 423: What is JScript?

Exposing PropertiesYou can expose properties in two ways:

As simple values The property is simply a global variable that can be read and written by the scriptcomponent's user. Because the value is stored in a global value, you can manipulate it in yourWindows® 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.

To expose a property as a simple value

Create a <public> element as a child of the <component> element.1. In the <public> element, include a <property> element that specifies the variable used to storeproperty value.

2.

To initialize the value of a simple property, create a global variable in the <script> element with aname matching propertyName (or propertyVariable, if you specified that) and assign it a value.

3.

The following script component fragment illustrates two properties (name and tag) exposed as simplevalues. The properties are initialized using global variables in the <script> element.

Note A CDATA section is required to make the script in the <script> elementopaque. 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>

4.

Exposing a property using functions is similar to exposing a method.

To expose a property using functions

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 notinclude the <put> element, the property will be read-only. If you do not include the <get> element,the property will be write-only.

1.

Write procedures in a <script> element outside the <public> element to implement the functions. Thefunction for setting the property's value � the put function � must accept a single parameter, the valueto 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 thefunction with the get_ prefix for a read function, and with a put_ prefix for the write function.

2.

For example, the following script component fragment is an example of a script component file thatexposes three properties: sname, dateOfBirth, and age. The dateOfBirth property is defined by

3.

Exposing Properties 1

Page 424: What is JScript?

functions so it can include error checking. The age property is calculated, and is therefore defined asread-only.

Note A CDATA section is required to make the script in the <script> elementopaque. 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 = gDOBEnd Function

Function writeDOB(newDOB) ' Sets value of dateOfBirth property. If isDate(gDOB) Then 'Error checking gDOB = newDOB End IfEnd 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

' Adjust if birthday has not yet occurred this year. bday = DateValue(dobM & "/" & dobD & "/" & todayY) If DateDiff("d", bday, DateValue(Date)) < 0 Then age = age - 1 End If readAge = age End IfEnd Function]]></script>

You can specify a default property for a script component so the host application can get or set the property'svalue without explicitly naming the property. For example, if you have exposed a property called sname andmarked it as the default, you can work with it in either of these ways in Visual Basic:

Set component = CreateObject("Component.MyComponent")n = component.sname ' Gets property explicitly.n = component ' Gets value of sname as default.

2 Exposing Properties

2 Exposing Properties

Page 425: What is JScript?

To specify a default property, include an attribute assigning a special dispatch identifier (a dispid) to themethod. For more information about dispids, see Exposing Events.

To specify a default property

In the <property> element, include the attribute dispid="0", as in the following example:

<property name="sname" dispid="0"/>

Note This technique can be used to assign either a default property or a defaultmethod, but not both. There can be only one element in the script component with thedispid of zero.

See Also

Exposing Events | Exposing Methods | Script Component File Contents | Script Component Files and XMLConformance

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

Exposing Properties 3

Exposing Properties 3

Page 426: What is JScript?

4 Exposing Properties

4 Exposing Properties

Page 427: What is JScript?

Exposing EventsTo add event capability to a Windows® Script Component:

Declare each event that you want to be able to fire.• Call a function to fire the event as required in the script component.•

Some host environments also require that you generate a type library which they use to bind to events. Fordetails, see Creating a Script Component Type Library.

Note The Behavior handler exposes events in a slightly different way. For details, seeExposing 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

Create a <public> element as a child of the <component> element.1. In the <public> element, include an <event> element for each event you want to declare.2. For example, the following script component fragment shows how to expose two events:

<public> <property name="sname"/> <method name="factorial"/> <event name="namechanged"/> <event name="querydone"/></public>

3.

Specifying Dispatch Identifiers

COM programming provides event notification via dispatch identifiers (each referred to as a dispid), whichare integer values that identify a component's events. The dispid is compiled into the component's type libraryand then used by the host application to bind to events.

The process of creating a type library for script components automatically generates dispids for your scriptcomponent'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 librarygenerator 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 tofire a standard COM event such as an error notification, you can map your event to the values used byconvention in COM.

To specify a dispid for an event, include the dispid attribute in the <event> element, as in the followingexample:

<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 toconventional events, but must use only specified ranges, such as -999 to -500 for controls. For details about

Exposing Events 1

Page 428: What is JScript?

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 moredetails, 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 cannotfire events that you did not expose in the <implements> element. You can fire an event in any script in yourscript component file. For example, the following illustrates how you can fire an event when a property valuechanges.

<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

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

2 Exposing Events

2 Exposing Events

Page 429: What is JScript?

Creating a Script Component Type LibraryYou can generate a type library for your Windows® Script Component containing information about itsinterfaces and members. In some host applications (such as Visual Basic), type libraries are necessary toenable 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 andless 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 ascript component's type library. This allows you to bind events to the script component and make them visiblein 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 caneasily 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 theapplication's documentation.

To create a script component type library

In Windows Explorer, right-click the script component .wsc file, and then choose Generate TypeLibrary.

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 fromscript inside the script component file, or you can use a command-line interface.

Generating Type Libraries Dynamically

The script component run-time includes an Automation interface implemented by theComponent.GenerateTypeLib object. You can use this object in script to generate a type library from withinthe script component file. This is particularly useful for creating a type library automatically when the scriptcomponent is registered.

To create a script component type library dynamically

In script inside the script component file, create an instance of the Component.GenerateTypeLibobject by using syntax such as the following:

set oTL = CreateObject("Scriptlet.GenerateTypeLib")

1.

Set the following properties of the Component.GenerateTypeLib object:Property/Method Description

AddURL (Method) Adds the URL of the script component file from which togenerate the type library. You can call this method property multipletimes to include multiple script components in the type library.

Path (Property) The path and file where the type library will be written.The default path is the current directory and the default name is thename of the script component file with a .tlb extension. If the objectis unable to create the specified library, it defaults to creating a typelibrary called component.tlb.

Doc (Property) A string containing any information that is stored in the

2.

Creating a Script Component Type Library 1

Page 430: What is JScript?

registry with the type library information.GUID (Property) A GUID for the type library. (This is not the GUID for

the script component.) If you do not provide one, theGenerateTypeLib object will create one, but then the type librarywill have a different GUID on each machine. The GUID must beexactly in this format, where x represents a hex value:

{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}

Name (Property) The internal name for the type library. This name isdisplayed in some applications, such as the Visual Basic ObjectBrowser.

MajorVersion (Property) An integer value you assign.MinorVersion (Property) An integer value you assign.Call the type library object's Write method to create the .tlb file, then register it.3. If you want to create an additional type library, call the GenerateTypeLib object's Reset method toclear the list of script component files in the AddURL property, reset the URLs and any otherproperties you want, and then call the Write method again.

4.

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. Fordetails, 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 tocreate type libraries.

To create a type library from the command prompt

Call Rundll32.exe using this syntax:

rundll32.exe path\scrobj.dll,GenerateTypeLib options

2 Creating a Script Component Type Library

2 Creating a Script Component Type Library

Page 431: What is JScript?

Where:

path The path where Scrobj.dll is located on your computer.• options A set of flags and values you can use to specify type library information in the form-flag:value. You can specify the options in any order. The following flags are supported, withvalues as described under the previous section, To create a script component type librarydynamically.

-name:Name-file:Path-doc:\"Doc\"-guid:GUID-major:MajorVersion-minor:MinorVersion-URL:AddURL

For example, the following command creates a type library called MyComponent.tlb from the scriptcomponent 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

Troubleshooting Type Libraries

The process of generating a type library can fail for various reasons. The error you see might not be clearenough in all cases to make it obvious where the problem lies. If you are unable to generate a type library,review the following list of likely causes for the failure.

If a property is defined by functions, the get and put functions must have the same number ofarguments with the same names. For details, see Exposing Properties.

Note It is possible to define a script component in which the get and put propertyfunctions have different numbers of arguments, but you cannot create a type libraryfor that script component.

If you are exposing events, you cannot use the same dispatch identifiers (dispid) more than once in ascript component. Additionally, you cannot use a negative value for the dispid unless it is within aspecified range. For details, see Exposing Methods.

The ID attributes of elements in the script component must be unique. If you are generating a typelibrary from more than one script component, then the IDs must be unique in the type library as awhole.

See Also

Script Component File Contents | Creating Registration Information | Checking For Errors in ScriptComponent Files | Script Component Files and XML Conformance

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Creating a Script Component Type Library 3

Creating a Script Component Type Library 3

Page 432: What is JScript?

Windows Script Components

4 Creating a Script Component Type Library

4 Creating a Script Component Type Library

Page 433: What is JScript?

Referencing Other ComponentsYour Windows® Script Component can include references to external components that you need to create thescript component, such as:

Additional COM objects• Type libraries• Resources, such as numbers and text, that you do not want to hard-code into your script component'sscripts.

Referencing Additional COM Components

In your script component, it might be necessary to create instances of other COM components as needed. Youcan do so in two ways:

In script Create instances of other objects directly in your script. For example, you can use theCreateObject function in Microsoft® Visual Basic® Scripting Edition (VBScript) or the newActiveXObject Object in JScript.

Using an OBJECT element Use an <object> element similar to the <OBJECT> tag you use inHTML pages. Using an <object> element makes objects globally available to any script and allowsscripting tools to provide statement completion. It also provides a convenient way to summarize anddocument the objects you use in your script component.

Note Although <object> elements in script components are similar to <OBJECT>tags in HTML pages, the list of attributes for an <object> element in a scriptcomponent is shorter, because script components do not present a user interface.

To create an OBJECT element

Create an <object> element. This element should be inside the <component> element, but outside ofany other element such as a <script> element.

The following example shows an object definition in a script component.

<object id="cnn" progid="ADODB.Connection"/>

Referencing an External Type Library

Many components that you might work with support type libraries, which provide a complete listing of thecomponent's classes and their members. By referencing the component's type libraries, you can use constantsdefined in the type library.

To include a reference to a type library

Include a <reference> element in your script component that specifies the location and name of thetype 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

Referencing Other Components 1

Page 434: What is JScript?

translated, and other values.

To reference resources

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 eachelement a unique ID. The following example shows two <resource> elements:

Note A CDATA section is required to make the contents of the <resource> elementopaque to the parser. For details, see Script Component Files and XMLConformance.

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

1.

In your script, include the resource text or number by calling the getResourcefunction, as shown in thefollowing example.

Note A CDATA section is required to make the script in the <script> elementopaque to the parser. For details, see Script Component Files and XMLConformance.

<script language="VBScript"><![CDATA[Function getRandomNumber(upperBound) If IsNumeric(upperBound) Then getRandomNumber = Cint(upperBound * Rnd + 1) Else getRandomNumber=getResource("errNonNumeric") End IfEnd Function]]></script>

2.

See Also

Script Component File Contents | Referencing Another Script Component in the Same Package

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

2 Referencing Other Components

2 Referencing Other Components

Page 435: What is JScript?

Referencing Another Script Component in theSame PackageYou can create a package that contains multiple Windows® Script Components, so you can also instantiateand use one of the script components from the other without having to register the second script component.

For example, you might create one script component that implements the Automation interface and exposes aseries of properties and methods. A second script component in the same package might implement the ASPinterface, 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 ASPscript component and makes its members available.

To reference one script component from another, create a skeleton member � a property or method � in onemethod that exposes the second script component.

To reference another script component in the same script component file

Declare a property or method in the first script component.1. As part of the definition for the new property or method, call the createComponentfunction.

For example, the following shows two script components in the same package. In the first scriptcomponent, the math method simply references the second script component, which exposes the addmethod and the multiply method.

Note A CDATA section is required to make the script in the <script> elementopaque. 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>

2.

Referencing Another Script Component in the Same Package 1

Page 436: What is JScript?

To invoke the referenced script component, call the full member hierarchy to get to its methods or properties.The following example illustrates a few ways to do this:

' Creates instance of first script component.set o1 = CreateObject("Component.FrontEnd")

' Invokes the second script component's functions directly.msgbox(o1.math.add(3,5))msgbox(o1.math.multiply(3,5))

' 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 scriptcomponent. If you need to preserve instance information between calls, store the pointer to the second scriptcomponent in a global variable, as in the following example.

Note A CDATA section is required to make the script in the <script> element opaque. Fordetails, 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>

(Component2 as in previous example)

See Also

Script Component File Contents | <package> | <component>

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

2 Referencing Another Script Component in the Same Package

2 Referencing Another Script Component in the Same Package

Page 437: What is JScript?

Checking For Errors in Script Component FilesBecause Windows® Script Components are used as COM components, they normally run silently. However,while you are developing your script component file, you might find it useful to know about errors in the file.You can specify three types of error checking:

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 componentfile, a generic error message is displayed. By specifying error notification, you can have the scriptcomponent parser display details about the error.

Allow debugging. By default, you cannot use the script debugger for script components. If you enabledebugging, you can launch the script debugger in response to an error, by setting a breakpoint, or witha Stop (Microsoft® Visual Basic® Scripting Edition (VBScript)) or debugger (JScript) statement.

Setting Error Options

Specify error options as attributes of the XML <?component?> processing instruction.

To specify error checking

Include the <?component?> processing instruction at the top of the script component file (but after theoptional <?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 thescript component.

debug Set this to true to enable debugging. If this debugging is not enabled, you cannotlaunch the script debugger for a script component in any way.

For example, the following enables all three error reporting options:

<?component error="true" debug="true"?>

Tip Turn error reporting off before deploying your script component to a productionenvironment.

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

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

Checking For Errors in Script Component Files 1

Page 438: What is JScript?

2 Checking For Errors in Script Component Files

2 Checking For Errors in Script Component Files

Page 439: What is JScript?

Using a Script Component in an ApplicationAfter creating a Windows® Script Component, you can use it as you would any COM component, by callingit from a host application such as Microsoft® Visual Basic®, C++, Microsoft® Internet Explorer, or otherapplications.

Note Script components written for DHTML Behaviors are instantiated differently thantraditional COM objects. For details, see Using DHTML Behaviors on the Microsoft SiteBuilder Network (SBN) Web site.

There are a variety of options for creating an instance of the script component, depending on the hostapplication, the type of script component you are using, and where the script component is deployed. Theprimary difference, however, is whether you want to create an instance of the script component locally (on thesame 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 andchange 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 scriptcomponent file. If you are working in an environment that supports statement completion, such as VisualBasic, you can see a script component's properties and methods if you generate and use a type library. Fordetails, 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 errorin the script component file. A parsing error in any XML element (including the <registration> element) cancause the instantiation to fail. While you are developing your script component file, set error checking optionsin 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 bya script component, the script component run-time can generate a type library, which containsinformation about the properties, methods, and events available in the script component. Fordetails, see Creating a Script Component Type Library.

Creating Local Instances of Script Components

If the script component is installed on the same computer as the host application, you can register the scriptcomponent as its own component as described in Registering a Script Component. You can then use the hostapplication's normal means for creating an object instance, such as the CreateObject function. For example,to create an instance of the script component that was registered with the program IDComponent.MyComponent in Visual Basic, use a statement such as this:

Set oComponent = CreateObject("Component.MyComponent")

Note If your host application is Visual Basic and you want to handle events fired by thescript component, you must bind the object early with a Dim statement that includes theWithEvents keyword, such as the following:Dim WithEvents scMyComponent As MyComponentPrivate Sub Command1_Click() Set scMyComponent=CreateObject("MyComponent")End Sub

Using a Script Component in an Application 1

Page 440: What is JScript?

Note For details, see Handling Script Component Events in the Host Application. This is notnecessary 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 mustknow 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 tocreate an instance of it. The moniker is supported in functions such as GetObject. The script componentrun-time, Scrobj.dll, must be registered on the local computer.

Note The GetObject function is not supported for script components in Microsoft® InternetExplorer for security reasons.

For example, the following illustrates how to call the Visual Basic GetObject function to create an instance ofan unregistered script component:

Set oComponent = GetObject("script:c:\COM\MyComponent.wsc")

If the .wsc file referenced by the moniker contains more than one script component, you can specify the scriptcomponent to instantiate by adding its name to the file name with a hash mark (#) as a delimiter. Thefollowing creates an instance of the script component whose ID is "math" contained in the fileMyComponent.wsc:

Set oComponent = GetObject("script:c:\COM\MyComponent.wsc#math")

Using a URL moniker allows you to create an instance of a script component that resides on anothercomputer, such as a Web server. Use a complete URL (with HTTP protocol) as the location for the scriptcomponent, as in the following example:

Set oComponent = GetObject("script:http://myserver/MyComponent.wsc")

Internet Explorer 5.0 supports DHTML Behavior syntax for creating instances of script components, whichworks somewhat differently than the traditional syntax for instantiating objects and will ensure that the scriptcomponent cannot access potential unsafe system objects. For an example, see Using DHTML Behaviors onthe Microsoft Site Builder Network (SBN) Web site.

Creating Remote Instances of Script Components

If the remotable attribute of a script component's <registration> element has been set to "true," the scriptcomponent can be instantiated remotely from another computer using Distributed COM (DCOM).

Both computers must have basic DCOM installed. A computer is correctly configured with DCOM if it isrunning 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 OSR2page on the Microsoft® Web site.

Windows 95 with DCOM for Windows 95, version 1.2. For details, see the DCOM for Windows 95page on the Microsoft® Web site.

2 Using a Script Component in an Application

2 Using a Script Component in an Application

Page 441: What is JScript?

The script component itself must be deployed as follows:

On the local computer, you do not require either the script component itself (.wsc file) or the scriptcomponent run-time (Scrobj.dll) at the time you instantiate the script component. However, you musthave 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. Bothmust be registered.

When you create an instance of a remote script component, it works within your application as if it were alocal object; you call its methods and get and set its properties normally. However, the remote scriptcomponent's script runs on the remote machine and has access to that machine's resources (within anylimitations imposed by security, and so forth). Communication between the host application on the localmachine 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 theremote computer as a parameter.

Note The ability to use CreateObject for instantiating remote script components requiresVisual 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":

Set newS = CreateObject("Component.MyComponent", "myserver")

Note There can be a slight delay when you first instantiate a remote script component whileDCOM establishes communication between the computers.

See Also

Creating Registration Information | Creating Script Components | How Script Components Work | IntroducingScript Components | Registering a Script Component

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

Using a Script Component in an Application 3

Using a Script Component in an Application 3

Page 442: What is JScript?

4 Using a Script Component in an Application

4 Using a Script Component in an Application

Page 443: What is JScript?

Handling Script Component Events in the HostApplicationMost host applications can receive Windows® Script Component events as they do any other events.However, some host applications require some setup before they can receive script component events.

Note If you are creating a Behavior script component, events are exposed using the DHTMLobject 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 receiveevents. Early binding requires a type library, so you must have generated a type library for the scriptcomponent. For details, see Creating a Script Component Type Library. In addition, when you declare theobject variable for the component, you must specify the WithEvents keyword. (The class name used in theDim statement is the ID that you assigned in the script component's <component> element.)

An example in Visual Basic might look like this:

Dim WithEvents Scriptlet1 as MyScriptletSet Scriptlet1 = CreateObject("MyScriptlet")Sub Scriptlet1_namechanged MsgBox("Value of name property changed")End Sub

See Also

Exposing Events

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

Handling Script Component Events in the Host Application 1

Page 444: What is JScript?

2 Handling Script Component Events in the Host Application

2 Handling Script Component Events in the Host Application

Page 445: What is JScript?

Creating a Behavior Script ComponentCreating a Behavior script component is similar to creating any other kind of script component, except thatyou are linking Microsoft® Internet Explorer events to script that is run in response to those events.

This topic is divided into the following sections:

Creating a Behavior Script Component File• Behavior-Related Enhancements to the DHTML Object Model• Getting Event Parameters in the Script Component• Scope Rules• Timing Considerations•

Creating a Behavior Script Component File

A Behavior script component includes an <implements> element that specifies the Behavior interface handler.Within the <implements> element, you use:

<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 alreadyavailable for the element in the containing document. For details, see Exposing Properties and Methods inBehavior Script Components.

The following example shows a Behavior script component that changes the color of an element in thecontaining page whenever the mouse is passed over the element. To do this, the sample binds the DHTMLonmouseover and onmouseout events to functions in the script component that set the element's DHTML styleattribute. The sample also sets the document's link color when the document is initialized by binding to theDHTML window object's onload event.

In addition to binding events to script, the script component also inserts text into any <H1> elements in thecontaining document that are linked to this script component. Finally, it exposes and fires an event calledonchange, 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. Fordetails, 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>

<attach event="onmouseover" handler="do_onmouseover"/> <attach event="onmouseout" handler="do_onmouseout"/>

<comment> This will call the init function when the onload event of window is fired.</comment>

<attach for="window" event="onload" handler="docinit"/>

<comment>The following defines HTML text that will appear in

Creating a Behavior Script Component 1

Page 446: What is JScript?

the containing document.</comment>

<layout> <h1>This is the HTML to show in the element</h1> </layout>

<comment>The following defines a custom event that is fired from within the script component by the fireEvent method.</comment>

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

There are a few things to point out in the preceding code:

From a script component procedure, the implied this pointer in an event handler refers to thecontaining 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 thesame behavior in the example exposed a property called hiliteColor, the inline scriptcould refer to hiliteColor directly (in other words, it resolves against the scriptcomponent's namespace). It is illegal, however, to refer to hiliteColor asBehavior.element.hiliteColor from an inline script, because at that point, the behaviorhas not yet been applied to the element. For more information, see Scope Rules andTiming Considerations later in this topic.

Behavior-Related Enhancements to the DHTML ObjectModel

The following enhancements were made to the DHTML object model for Microsoft® Internet Explorer 5 inorder to add support for behaviors.

2 Creating a Behavior Script Component

2 Creating a Behavior Script Component

Page 447: What is JScript?

The cascading style sheet (CSS) behavior attribute specifies the location of the behavior.• The DHTML attachEvent and detachEvent methods enable a Behavior script component to receiveevent notifications from the containing page, by specifying a function that gets called whenever theevent fires on the object.

The DHTML uniqueID property enables a behavior script component to assign an ID to the element.This can be useful in cases where a script component injects code into the containing page and needsto specify the ID of the element to which the behavior is being applied.

Getting Event Parameters in the Script Component

In DHTML, the DHTML event object provides information about the event. Although in DHTML the eventobject is accessible to event handlers through the DHTML window object, in a behavior script component theevent object is passed in as a parameter to the event handler.

The following code from a hypothetical calculator script component demonstrates keyboard and mouse eventsbound to a script component function called doCalc. The doCalc function uses the event object to getinformation about the conditions under which the event was fired.

Note A CDATA section is required to make the script in the <script> element opaque. Fordetails, 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 behaviorscript 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, abehavior-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 theelement.

Finally, the name is resolved to the name of a property, method, or event that applies to the window object inthe containing page.

Creating a Behavior Script Component 3

Creating a Behavior Script Component 3

Page 448: What is JScript?

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 thebehavior has been applied, scripts cannot have access to the values of behavior-defined properties that mightbe set in the document.

Because the behavior is encapsulated in a separate file from the HTML document, it is downloaded separatelyfrom the rest of the document. As the document and behavior are parsed and loaded, the behavior receivesnotifications of progress through the function specified with the attachNotification method. Currently, thebehavior 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 sentwhen 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 valuesof behavior-defined attributes and properties that are being set in the document may not be accessible from aninline script. However, these properties will be available as soon as the first "contentChange" notification issent.

See Also

Exposing Properties and Methods in Behavior Script Components | Exposing Custom Events in BehaviorScript Components | Behavior Handler Reference

© 2001 Microsoft Corporation. All rights reserved.

4 Creating a Behavior Script Component

4 Creating a Behavior Script Component

Page 449: What is JScript?

Build: Topic Version 5.6.9309.1546

Windows Script Components

Creating a Behavior Script Component 5

Creating a Behavior Script Component 5

Page 450: What is JScript?

6 Creating a Behavior Script Component

6 Creating a Behavior Script Component

Page 451: What is JScript?

Exposing Properties and Methods in BehaviorScript ComponentsBehavior script components can expose custom properties and methods in a manner similar to Automationscript components. Behavior script component properties and methods extend the properties and methodsavailable to elements in the containing page. For example, you might create a behavior script component thatchanges the color of an element when the mouse is passed over it. By defining a property in the scriptcomponent, you can make available a custom property in the document, perhaps called hiliteColor, thatallows the Web page author to set the color with which text gets highlighted.

A behavior can override an element's default behavior by exposing a property or method of the same name asthat which is already defined for the element.

Properties and methods are defined in a <public> element separate from the <implements> element used tospecify 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 componentfragment shows a Behavior script component that exposes the custom property hiliteColor. If the containingpage 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. Fordetails, 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 scriptcomponent. For details, see Exposing Methods. In a Behavior script component, methods exposed in the scriptcomponent extend those already available for the element in the containing document.

See Also

Exposing Custom Events in Behavior Script Components

Exposing Properties and Methods in Behavior Script Components 1

Page 452: What is JScript?

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

2 Exposing Properties and Methods in Behavior Script Components

2 Exposing Properties and Methods in Behavior Script Components

Page 453: What is JScript?

Exposing Custom Events in Behavior ScriptComponentsBehavior script components, like Automation script components, can expose custom events that are firedinside the script component and can be handled in the containing document. An event is declared in the<public> element as in the following:

<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 isalready defined for the element. For example, a behavior that exposes an onclick event can override theelement's default onclick event.

Getting and Setting Custom Event Information

Your custom script component event can get access to the DHTML event object, which maintainsevent-specific information. You can use this object to:

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 eventback 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 canpass 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 followingshows 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® (orJavaScript). 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 sampledefines 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. Fordetails, see Script Component Files and XML Conformance.

Exposing Custom Events in Behavior Script Components 1

Page 454: What is JScript?

<public> <event name="onResultChange" /></public>

<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 ofthe calculation are extracted from expando property result of the DHTML window.event object and displayedin 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>

<LK:CALC id="myCalc" onResultChange="showResults()"><TABLE><TR> <DIV ID=resultWindow STYLE="border: '.025cm solid gray'" ALIGN=RIGHT>0.</DIV></TR><TR> <TD><INPUT TYPE=BUTTON VALUE=" 0 "></TD> <TD><INPUT TYPE=BUTTON VALUE="+/-"></TD> <TD><INPUT TYPE=BUTTON VALUE=" . "></TD> <TD><INPUT TYPE=BUTTON VALUE=" + "></TD> <TD><INPUT TYPE=BUTTON VALUE=" = "></TD><TR></TABLE></LK:CALC></HTML>

See Also

Exposing Properties and Methods in Behavior Script Components

© 2001 Microsoft Corporation. All rights reserved.

2 Exposing Custom Events in Behavior Script Components

2 Exposing Custom Events in Behavior Script Components

Page 455: What is JScript?

Build: Topic Version 5.6.9309.1546

Windows Script Components

Exposing Custom Events in Behavior Script Components 3

Exposing Custom Events in Behavior Script Components 3

Page 456: What is JScript?

4 Exposing Custom Events in Behavior Script Components

4 Exposing Custom Events in Behavior Script Components

Page 457: What is JScript?

<implements> ElementSpecifies additional COM interface handlers for a script component.

<implements type="COMHandlerName" [id="internalName"] [default=fAssumed]> handler-specific information here</implements>

Values

COMHandlerNameThe 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 scriptcomponent. Some handlers, such as the Automation and ASP handlers, are built into the scriptcomponent run-time (Scrobj.dll). Examples of available interface handlers include:

Interface handler Description How implementedASP Allows a script component to

get access to the MicrosoftInternet Information Services(IIS) Active Server Pages(ASP) object model.

Built into Scrobj.dll

DHTML Behaviors Allows a behavior scriptcomponent to communicatewith the containing page so itcan fire events and access theDHTML object model.

Built into Scrobj.dll

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 bedisambiguated by prefixing them with the ID of the <implements> element to which they belong, asin the following:

<implements type="Behavior" id="sctBehavior"> [...]</implements>

[...]

<script language="JScript"> // [...] sctBehavior.fireEvent("onResultChange",oEvent);</script>

fAssumed(Optional) A Boolean flag indicating that the internalName is assumed in scripts. The default valuefor this attribute is true, and members of the object model exposed by the handler are added to theglobal script namespace and can be accessed unqualified. You only need to include this attribute ifyou 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

Page 458: What is JScript?

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

How Script Components Work | Script Component File Contents

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

2 <implements> Element

2 <implements> Element

Page 459: What is JScript?

<property> ElementDeclares a property.

<property name="propertyName" [internalName="propertyVariable"] />

�or�

<property name="propertyName"> <get [internalName="getFunctionName"] /> <put [internalName="putFunctionName"] /></property>

Values

propertyNameThe name of the property to expose. Unless you specify an internalName attribute, this name mustmatch 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 thevalue for propertyName. If you do not include the internalName attribute, the property value ismaintained in a variable named the same as propertyName. Specifying the internalName attributeallows 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 donot specify an internalName attribute, the method used to read the property value must have the nameof 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> elementbut do not specify an internalName attribute, the method used to read the property value must havethe 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 thescript component file.

You can also implement properties as procedures (functions or subroutines), which allows you to calculate aproperty 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 theprocedures 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 theproperty.

In addition to the standard syntax shown above, you can use a shorthand notation to specify information whatwould 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

Page 460: What is JScript?

<property name="myproperty" get put/>

which is functionally equivalent to:

<property name="myproperty"> <get/> <put/></property>

If you wanted to explicitly name those accessors differently from the default, you can use the followingsyntax:

<property name="myproperty" get="testget" put="testput"/>

To specify a default property, include the attribute dispid="0" in the <property> element. For details, seeExposing 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 withthe function readAge. The dateOfBirth property is read-write, and is implemented wih the functions readDOBand writeDOB. Finally, the mstatus property is implemented with the default functions get_mstatus andput_mstatus.

Note A CDATA section is required to make the script in the <script> element opaque. Fordetails, 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 = gDOBEnd Function

Function writeDOB(newDOB) ' Sets value of dateOfBirth property. If isDate(gDOB) Then ' Error checking. gDOB = newDOB End IfEnd Function

2 <property> Element

2 <property> Element

Page 461: What is JScript?

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

' Adjust if birthday has not yet occurred this year. bday = DateValue(dobM & "/" & dobD & "/" & todayY) If DateDiff("d", bday, DateValue(Date)) < 0 Then age = age - 1 End If readAge = age End IfEnd Function

Function get_mstatus() ' Reads value of mstatus property. get_mstatus = gMStatusEnd Function

Function put_mstatus(s) ' Writes value of mstatus property. If s = "M" Or s = "S" Then gMStatus = s Else gMStatus = "?" End IfEnd Function]]></script>

See Also

<event> Element | <method> Element | Exposing Events | Exposing Methods | Exposing Properties

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

<property> Element 3

<property> Element 3

Page 462: What is JScript?

4 <property> Element

4 <property> Element

Page 463: What is JScript?

<public> ElementEncloses 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 | ExposingProperties

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

<public> Element 1

Page 464: What is JScript?

2 <public> Element

2 <public> Element

Page 465: What is JScript?

<reference> ElementIncludes a reference to an external type library.

<reference [object="progID" |guid="typelibGUID"] [version="version"]>

Values

progIDThe program ID from which the type library can be derived, which can include a version number (forexample, ADO.Recordset.2.0). This can include the explicit program ID of a type library, or theprogram ID of the executable (such as a .DLL) that incorporates the type library. If you use the objectattribute, you do not need to specify a version attribute, because the version can be inferred from theprogram 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 anobject attribute.

version(Optional) The version number of the type library to use. It must be in the form <majorversion>[.<minor version>]. If a version is not specified, the default version is 1.0. If the objectattribute is used to specify the type library and the version is not specified, the version is derived fromthe 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 inscripts. The <reference> element looks up and makes available the type library associated with a specificprogram 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 scriptcomponent 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 fileMSAD015.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. Fordetails, 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 cnnDim cnnStateFunction openConnection() Set cnn = CreateObject("ADODB.Connection")

<reference> Element 1

Page 466: What is JScript?

cnn.ConnectionString = "driver={SQL Server};server=myserver;uid=sa;database=pubs" cnn.Open If cnn.State = adStateOpen Then cnnState = "open" Else cnnState = "closed" End IfEnd Function

Function closeConnection() cnn.Close cnnState = "closed"End Function]]></script>

See Also

Referencing Other Components

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

2 <reference> Element

2 <reference> Element

Page 467: What is JScript?

<registration> ElementDefines information used to register the script component as a COM component.

<registration progid="progID" classid="GUID" description="description" version="version" [remotable=remoteFlag]/>

�or�

<registration progid="progID" classid="GUID" description="description" version="version" [remotable=remoteFlag]>

<script>(registration and unregistration script)

</script></registration>

Values

progID(Optional) A text name that programmers use to reference your script component when creating aninstance of it. For example, if your script component's program ID is Component.MyComponent, youcan create an instance of it in Microsoft® Visual Basic using a statement such as the following:

Set Component = CreateObject("Component.MyComponent")

Note Although a progid attribute is optional, you must include either a progid or aclassid attribute (you can include both). If only the progid attribute is specified, theclass ID is generated automatically. If only the class ID is created, then no progid isregistered 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 asUuidgen.exe). If you do not include a class ID, the registration program assigns a class ID to yourscript component.

description(Optional) A text description of the script component that is stored in the registry and that is used incertain tools such as the Visual Basic object browser.

version(Optional) A numeric version number that you assign. The version is appended to the program IDwith a period (for example, MyComponent.1) when applications request a version-specific name. Useonly 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 remotelyusing DCOM. For details, see Creating Remote Instances of Script Components in the topic "Using aScript Component in an Application."

Remarks

After a script component is created, it can be registered using a program such as Regsvr32.exe, which readsthe information in the <registration> element and writes it into the computer's Windows Registry. Forexample, a script component can be registered this way:

regsvr32 file:\\myserver\MyComponent.wsc

<registration> Element 1

Page 468: What is JScript?

Note A <registration> element is not required in all cases. For example, a script componentthat implements the DHTML Behaviors interface handler in Microsoft® Internet Explorer 5.0does not need to be registered, because Internet Explorer registers the behaviors as they aredetected on the page. For details about registration requirements, see the documentation forthe interface handler you are implementing and note also which host the script componentwill be used in.

If you do not include class ID information, the registration program assigns a class ID to your scriptcomponent at the time it is registered. However, the script component will have a different class IDeverywhere it is registered. It is highly recommended that you provide a class ID for the script componentyourself, to ensure that your script component has the same class ID on all computers on which it isregistered.

Allowing the registration program to create a class ID can cause problems if you use the script componentwith development tools that store class IDs. If the registration creates a new class ID each time, it will notmatch 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 scriptcomponent is registered and unregistered.

Note A CDATA section is required to make the script in the <script> element opaque. Fordetails, 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

2 <registration> Element

Page 469: What is JScript?

</script> ]]></registration>

See Also

Creating Registration Information | Registering a Script Component

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

<registration> Element 3

<registration> Element 3

Page 470: What is JScript?

4 <registration> Element

4 <registration> Element

Page 471: What is JScript?

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

ResourceIDA 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 tointermingle with script in your script component. For example, resource elements are typically used tomaintain 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 howto use it in script.

Note A CDATA section is required to make the script in the <script> element opaque. Fordetails, 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 IfEnd Function]]></script>

See Also

Referencing Other Components

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

<resource> Element 1

Page 472: What is JScript?

Windows Script Components

2 <resource> Element

2 <resource> Element

Page 473: What is JScript?

<script> ElementDefines the script component's behavior.

<script language="language">script here

</script>

Values

languageThe name of the scripting language used in the script component file, such as Microsoft® VisualBasic® Scripting Edition (VBScript) or JScript.

Remarks

If XML validation is not enabled, the XML parser ignores all lines inside the <script> element. However, ifXML validation is enabled by including the <?XML ?> declaration at the top of the script component file, theXML parser can misinterpret greater than (<), less than (>), and other symbols used in script as XMLdelimiters.

If you are creating a file that conforms closely to XML syntax, you must make sure that characters in yourscript 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 XMLConformance.

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 IfEnd Function]]></script></component>

See Also

Script Component File Contents

<script> Element 1

Page 474: What is JScript?

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

2 <script> Element

2 <script> Element

Page 475: What is JScript?

<component> ElementEncloses an entire Windows Script Component definition.

<component id=componentid> script component information here</component>

Values

componentidA string that uniquely identifies the script component. This value is useful if a document containsmultiple 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 ascript 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, thescript component is identified as the class MyComponent in the Visual Basic object browser. If nocomponent 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 scriptcomponents, 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 nameproperty.

Note A CDATA section is required to make the script in the <script> element opaque. Fordetails, 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

Page 476: What is JScript?

factorial = -2 ' Error code. End If End Function ]]></script></component>

See Also

Script Component File Contents

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

2 <component> Element

2 <component> Element

Page 477: What is JScript?

<attach> ElementBinds an event from the containing document to a function in the script component.

<attach event="eventName" handler="functionName" [for="elementName"]/>

Values

eventNameThe event being bound, such as onmouseclick.

functionNameThe name of the procedure (function or subroutine) in the script component file that is executed inresponse 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 eventattribute. If the for attribute is specified, the default handler attribute value is the string generated byconcatenating the for attribute value, "_", and the event attribute value.

elementNameThe element associated with the event, used for containing elements to which DHTML Behaviors arenot 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 befired 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 DHTMLonmouseover element is bound to the script component's do_onmouseover function. The functions bound tothe DHTML onmouseover and onmouseout events are executed only if they are fired on the element in thecontaining document to which the behavior is attached. The docinit function is explicitly bound to theDHTML document object's onload event.

Note A CDATA section is required to make the script in the <script> element opaque. Fordetails, 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

Page 478: What is JScript?

}]]></script></component>

See Also

Creating a Behavior Script Component

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

2 <attach> Element

2 <attach> Element

Page 479: What is JScript?

element PropertyReturns the element to which the behavior is being applied.

[oElement = ] Behavior.element

Values

oElementElement to which the behavior is being applied.

BehaviorThe ID of the <implements> element used to implement the Behavior interface.

Note By default, the properties and methods exposed by the Behavior handler areautomatically added to the global script namespace and can be accessed withoutreferencing the Behavior handler ID. In this case, instead of using Behavior.elementas shown in the syntax, the property can be used in script simply as element. Formore details, see the <implements> element.

Remarks

The property is read-only.

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 ascript component. The script component attaches to the element's DHTML onmouseover event. It sets theDHTML cursor property of the element to "hand" to signal the user that the element can be clicked in orderto toggle visibility of its children.

Note A CDATA section is required to make the script in the <script> element opaque. Fordetails, 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

Page 480: What is JScript?

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Windows Script Components

2 element Property

2 element Property

Page 481: What is JScript?

<layout> ElementDefines HTML text inserted into the containing document.

<layout> <HTMLtag>Inserted text</HTMLtag></layout>

Values

HTMLTagThe 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 thecontaining 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 areopaque. However, if the script component is XML-conformant, the contents of the <layout> element mustexplicitly be made opaque by including them in a CDATA. For more details, see Script Component Files andXML Conformance.

Example

The following shows an example of a script component with a <layout> element. Because the scriptcomponent contains the <?XML ?> declaration at the top, the <layout> element contains a CDATA section tomake the contents of the <layout> element opaque to the XML parser.

<?XML version="1.0" ?><component id="bvrScriptlet1"><registration progID="BehaviorScriptlet"/><implements type="Behavior"> <layout> <![CDATA[ <h1>This is the HTML to show in the element</h1> ]]> </layout></implements></component>

See Also

For general information about applying behaviors to DHTML elements, see the "Using DHTML Behaviors"topic on the Site Builder Network (SBN).

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546

Microsoft® Windows® Script Interfaces

Microsoft Windows ScriptInterfaces-Introduction

Language ReferenceNext

<layout> Element 1

Page 482: What is JScript?

Microsoft® Windows® Script Interfaces introduce a new way for an application to addscripting and OLE Automation capabilities. With the advent of the interfaces, hosts can callupon disparate scripting engines from multiple sources and vendors to perform scriptingbetween components. The implementation of the script itself�language, syntax, persistentformat, execution model, and so on�is left to the script vendor. The designers have taken careto allow hosts that rely on Windows Script to use arbitrary language back ends.

Windows Script Hosts♦ Windows Script Engines♦ IDispatchEx♦ IProvideMultipleClassInfo♦ Active Script Debugging Interfaces♦

Windows Script Terms

This list contains definitions of the scripting-related terms used in this document.

Term Definition

Codeobject

An instance created by the scripting engine that is associated with anamed item, such as the module behind a form in Visual Basic®, or a C++class associated with a named item. Preferably, this is an OLE ComponentObject Model (COM) object that supports OLE Automation so the host orother nonscript entity can manipulate the code object.

Nameditem

An OLE COM object (preferably one that supports OLE Automation) thatthe host deems interesting to the script. Examples include the HTML Pageand Browser in a Web browser, and the Document and Dialogs inMicrosoft Word.

Script The data that makes up the program that the scripting engine runs. A scriptcan be any contiguous executable data, including pieces of text, blocks ofpcode, or even machine-specific executable byte codes. A host loads ascript into the scripting engine through one of the IPersist* interfaces orthrough the IActiveScriptParse interface.

Scriptingengine

The OLE object that processes scripts. A scripting engine implements theIActiveScript and, optionally, IActiveScriptParse interfaces.

Scriptinghost

The application or program that owns the Windows Script engine. The hostimplements the IActiveScriptSite and, optionally, IActiveScriptSiteWindowinterfaces.

Scriptlet A portion of a script that gets attached to an object through theIActiveScriptParse interface. The aggregate collection of scriptlets is thescript.

Scriptlanguage

The language in which a script is written (VBScript, for example) and thesemantics of that language.

Windows Script Background

Windows Script components fall into two categories: Windows Script hosts and WindowsScript engines. A host creates a scripting engine and calls on the engine to run the scripts.Examples of Windows Script hosts include:

Microsoft Internet Explorer♦ Internet authoring tools♦ Shell♦

Windows Script engines can be developed for any language or run-time environment,including:

Microsoft Visual Basic Scripting Edition (VBScript)♦ Perl♦

2 <layout> Element

2 <layout> Element

Page 483: What is JScript?

Lisp♦ To make implementation of the host as flexible as possible, an OLE Automation wrapper forWindows Script is provided. However, a host that uses this wrapper object to instantiate thescripting engine does not have the degree of control over the run-time name space, thepersistence 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 authoringenvironment so that nonauthoring hosts (such as browsers and viewers) and script engines(for example, VBScript) can be kept lightweight.

Windows Script Basic Architecture

The following illustration shows the interaction between an Windows Script host and anWindows Script engine.

Following is a description of the steps involved in the interaction between the host andengine. The actual nesting of the function calls is omitted for clarity.

Create a Project. The host loads a project or document. (This step is not particular toWindows Script, but is included here for completeness.)

1.

Create the Windows Script Engine. The host calls CoCreateInstance to create a newWindows Script engine, specifying the class identifier (CLSID) of the specific scripting engineto use. For example, the HTML browsing component of Internet Explorer receives the scriptingengine's class identifier through the CLSID= attribute of the HTML <OBJECT> tag.

2.

Load the Script. If the script contents have been persisted, the host calls the script engine'sIPersist*::Load method to feed it the script storage, stream, or property bag. Otherwise, thehost uses either the IPersist*::InitNew or IActiveScriptParse::InitNew method to create a nullscript. A host that maintains a script as text can use IActiveScriptParse::ParseScriptText tofeed the scripting engine the text of the script, after calling IActiveScriptParse::InitNew.

3.

Add Named Items. For each top-level named item (such as pages and forms) imported intothe scripting engine's name space, the host calls the IActiveScript::AddNamedItem method tocreate an entry in the engine's name space. This step is not necessary if top-level named itemsare already part of the persistent state of the script loaded in step 3. A host does not useIActiveScript::AddNamedItem to add sublevel named items (such as controls on an HTMLpage); rather, the engine indirectly obtains sublevel items from top-level items by using thehost's ITypeInfo and IDispatch interfaces.

4.

Run the Script. The host causes the engine to start running the script by setting theSCRIPTSTATE_CONNECTED flag in the IActiveScript::SetScriptState method. This call wouldlikely perform any scripting engine construction work, including static binding, hooking up toevents (see below), and executing code, in a way similar to a scripted main() function.

5.

Get Item Information. Each time the script engine needs to associate a symbol with atop-level item, it calls the IActiveScriptSite::GetItemInfo method, which returns information

6.

<layout> Element 3

<layout> Element 3

Page 484: What is JScript?

about the given item.Hook Up Event Advise. Before starting the actual script, the scripting engine connects to theevents of all the relevant objects through the IConnectionPoint interface.

7.

Invoke Properties and Methods. As the script runs, the scripting engine realizes referencesto methods and properties on named objects through IDispatch::Invoke or other standardOLE binding mechanisms.

8.

Microsoft® Windows® Script Interfaces

Windows Script HostsLanguage Reference

PreviousNext

When implementing Microsoft® Windows® Script host, you can safely assume that ascripting engine will only call the IActiveScriptSite interface in the context of the base threadas 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 modeldescribed above is intentionally loose enough to allow a host to abort a stuck script by callingIActiveScript::InterruptScriptThread from another thread (initiated by a CTRL+BREAK handleror 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-threadedIActiveScriptSite interface and a free-threaded object model. Such a host can use theIActiveScript interface from any thread, without restriction.

Microsoft® Windows® Script Interfaces

Windows Script EnginesLanguage Reference

PreviousNext

To implement an Microsoft® Windows® Script engine, create an OLE COM object thatsupports the following interfaces.

Interface Description

IActiveScript Provides the basic scripting ability. Implementation of this interfaceis required.

IActiveScriptParse Provides the ability to add script text, evaluate expressions, and soon. Implementation of this interface is optional; however, if it is notimplemented, the script engine must implement one of theIPersist* interfaces in order to load a script.

IPersist* Provides persistence support. Implementation of at least one of thefollowing interfaces is required if IActiveScriptParse is notimplemented.Interface Description

IPersistStorage Provides support for the DATA={url}attribute in the OBJECT tag.

IPersistStreamInit Provides support for the same asIPersistStorage as well as theDATA="string-encoded byte stream"attribute in the OBJECT tag.

IPersistPropertyBag Provides support for the PARAM= attributein the OBJECT tag.

4 <layout> Element

4 <layout> Element

Page 485: What is JScript?

Note: It is possible that the scripting engine will never be called upon to save or restore ascript state through IPersist*. Instead, IActiveScriptParse is used by callingIActiveScriptParse::InitNew to create a blank script, then scriptlets are added and connectedto events with IActiveScriptParse::AddScriptlet and general code is added withIActiveScriptParse::ParseScriptText. Nonetheless, a scripting engine should fully implementat least one IPersist* interface (preferably IPersistStreamInit), because other hostapplications 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♦

See the Script Interface Reference for more information.

Registry Standard

An Windows Script engine can identify itself using component categories.Windows Script currently defines two component categories.

Category Decription

CATID_ActiveScript Indicates that the class identifiers (CLSIDs)are Windows Script engines that support, ata minimum, the IActiveScript interface and apersistence mechanism (theIPersistStorage, IPersistStreamInit, orIPersistPropertyBag interface).

CATID_ActiveScriptParse Indicates that the CLSIDs are WindowsScript engines that support, at a minimum,the IActiveScript and IActiveScriptParseinterfaces.

Although IActiveScriptParse is not a true persistence mechanism, it doessupport the IActiveScriptParse::InitNew method that is functionallyequivalent to IPersist*::InitNew.

Script Engine States

At any given time, an Windows Script engine can be in one of several states.

State Descriptioon

uninitialized The script has not been initialized or loaded using anIPersist* interface, or does not have an IActiveScriptSiteinterface set. The scripting engine is generally not usablefrom this state until the script is loaded.

initialized The script has been initialized with an IPersist* interfaceand has an IActiveScriptSite interface set, but is notconnected to host objects and sinking events. Note thatthis state simply means that the IPersist*::Load,IPersist*::InitNew, or IActiveScriptParse::InitNewmethod has been completed, and that theIActiveScript::SetScriptSite method has been called. Theengine cannot run code in this mode. The engine queuescode that the host passes to it through theIActiveScriptParse::ParseScriptText method, andexecutes the code after transitioning to the started state.

<layout> Element 5

<layout> Element 5

Page 486: What is JScript?

Because languages can vary widely in semantics,scripting engines are not required to support thisstate transition. Engines that support theIActiveScript::Clone method must, however,support this state transition. Hosts must prepare forthis transition and take the appropriate action:release the current scripting engine, create a newscripting engine, and call IPersist*::Load,IPersist*::InitNew, orIActiveScriptParse::InitNew (and possibly also callIActiveScriptParse::ParseScriptText). Use of thistransition should be considered an optimization ofthe above steps. Note that any information thescripting engine has obtained about the names ofNamed Items and the type information describingNamed Items remains valid.

Because languages vary widely, defining the exactsemantics of this transition is difficult. At aminimum, the scripting engine must disconnectfrom all events, and release all of theSCRIPTINFO_IUNKNOWN pointers obtained bycalling the IActiveScriptSite::GetItemInfo method.The engine must re-obtain these pointers after thescript is run again. The scripting engine should alsoreset the script back to an initial state that isappropriate for the language. VBScript, forexample, resets all variables and retains any codeadded dynamically by callingIActiveScriptParse::ParseScriptText with theSCRIPTTEXT_ISPERSISTENT flag set. Otherlanguages may need to retain current values (suchas Lisp because there is no code/data separation) orreset to a well-known state (this includes languageswith statically initialized variables).

Note that the transition to the started state shouldhave the same semantics (that is, it should leavethe scripting engine in the same state) as callingIPersist*::Save to save the scripting engine, andthen calling IPersist*::Load to load a newscripting engine; these actions should have thesame semantics as IActiveScript::Clone. Scriptingengines that do not yet supportIActiveScript::Clone or IPersist* shouldcarefully consider how the transition to the startedstate should behave, so that such a transition wouldnot violate the above conditions ifIActiveScript::Clone or IPersist* support waslater added.

During this transition to the started state, thescripting engine will disconnect from event sinksafter the appropriate destructors, and so on, are

6 <layout> Element

6 <layout> Element

Page 487: What is JScript?

executed in the script. To avoid having thesedestructors executed, the host can first move thescript into the disconnected state before movinginto the started state.

Use IActiveScript::InterruptScriptThread to cancela running script thread without waiting for currentevents, and so on, to finish running.

started The transition from the initialized state to the startedstate causes the engine to execute any code that wasqueued in the initialized state. The engine can executecode while in the started state, but it is not connected toany events added through theIActiveScript::AddNamedItem method. The engine canexecute code by calling the IDispatch interface obtainedfrom the IActiveScript::GetScriptDispatch method, or bycalling IActiveScriptParse::ParseScriptText. It is possiblethat further background initialization (progressiveloading) is still ongoing, and that calling theIActiveScript::SetScriptState method with theSCRIPTSTATE_CONNECTED flag set may cause thescript to block until initialization is complete.

connected The script is loaded and connected for sinking eventsfrom host objects. If this is a transition from the initializedstate, the scripting engine should transition through thestarted state, performing the necessary actions, beforeentering the connected state and connecting to events.

disconnected The script is loaded and has a run-time state, but istemporarily disconnected from sinking events from hostobjects. This can be done either logically (ignoringevents received) or physically (callingIConnectionPoint::Unadvise on the appropriateconnection points). If this is a transition from theinitialized state, the scripting engine should transitionthrough the started state, performing the necessaryactions, before entering the disconnected state. Eventsinks that are in progress are completed before the statechanges (use IActiveScript::InterruptScriptThread tocancel a running script thread). This state isdistinguished from the initialized state in that thetransition to this state does not cause the script to reset,the run-time state of the script is not reset, and a scriptinitialization procedure is not executed.

closed The script has been closed. The scripting engine nolonger works and returns errors for most methods.

The following illustration shows the relationships between the variousscripting engine states, and shows the methods that cause transitions fromone state to another.

<layout> Element 7

<layout> Element 7

Page 488: What is JScript?

The following illustration shows the actions that the scripting engineperforms during the various state transitions.

Scripting Engine Threading

Because an Windows Script engine can be used in many environments, it isimportant to keep its execution model as flexible as possible. For example, aserver-based host may need to preserve a multithreaded design while usingWindows Script in an efficient manner. At the same time, a host that does notuse threading, such as a typical application, should not be burdened withthreading management. Windows Script achieves this balance by restrictingthe ways a free-threaded scripting engine can call back to the host, freeinghosts from this burden.

Scripting engines used on servers are typically implemented as free-threadingCOM objects. This means that methods on the IActiveScript interface and itsassociated interfaces can be called from any thread in the process, without

8 <layout> Element

8 <layout> Element

Page 489: What is JScript?

marshaling. (Unfortunately, this also means that the scripting engine must beimplemented as an in-process server, because OLE does not currently supportinterprocess marshaling of free-threaded objects.) Synchronization is theresponsibility of the scripting engine. For scripting engines that are notinternally reentrant, or for language models that are not multithreaded,synchronization could be as simple as serializing access to the scriptingengine with a mutex. Of course certain methods, such asIActiveScript::InterruptScriptThread, should not be serialized in this way sothat a stuck script can be terminated from another thread.

The fact that IActiveScript is typically free-threaded generally implies thatthe IActiveScriptSite interface and the host's object model should befree-threaded as well. This would make implementation of the host quitedifficult, particularly in the common case where the host is a single-threadedMicrosoft Windows®-based application with single-threaded orapartment-model ActiveX Controls in its object model. For this reason, thefollowing constraints are placed on the scripting engine's use ofIActiveScriptSite:

The script site is always called in the context of a host thread. That is, thescripting engine never calls the script site in the context of a thread that thescripting engine created, but only from within a scripting engine method thatwas called from the host through IActiveScript and its derivatives, throughthe 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 statecontrol method (for example, the IActiveScript::InterruptScriptThreadmethod) or from the IActiveScript::Clone method.

Microsoft® Windows® Script Interfaces

Windows Script Interface ReferenceLanguage Reference

PreviousNext

The following interfaces are specific to Microsoft® Windows® Script hosts:

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♦

Microsoft® Windows® Script Interfaces

IActiveScriptLanguage Reference

PreviousNext

The IActiveScript interface provides the methods necessary to initialize the scripting engine.The scripting engine must implement the IActiveScript interface.

Methods in Vtable Order

Method Description

<layout> Element 9

<layout> Element 9

Page 490: What is JScript?

SetScriptSite Informs the scripting engine of the IActiveScriptSite siteprovided by the host.

GetScriptSite Retrieves the site object associated with the WindowsScript engine.

SetScriptState Places the scripting engine into the specified state.

GetScriptState Retrieves the current state of the scripting engine.

Close Causes the scripting engine to abandon any currentlyloaded script, lose its state, and release any interfacepointers it has to other objects, thus entering a closed state.

AddNamedItem Adds the name of a root-level item to the scripting engine'sname space.

AddTypeLib Adds a type library to the name space for the script.

GetScriptDispatch Retrieves the IDispatch interface for the running script.

GetCurrentScriptThreadID Retrieves a scripting-engine-defined identifier for thecurrently executing thread.

GetScriptThreadID Retrieves a scripting-engine-defined identifier for the threadassociated with the given Microsoft Win32® thread.

GetScriptThreadState Retrieves the current state of a script thread.

InterruptScriptThread Interrupts the execution of a running script thread.

Clone Clones the current scripting engine (minus any currentexecution state), returning a loaded scripting engine thathas no site in the current thread.

Microsoft® Windows® Script Interfaces

IActiveScript::AddNamedItemLanguage Reference

PreviousNext

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 withproperties and methods, an event source, or all three.

Returns one of the following values:

Return Value Meaning

S_OK Success.

E_INVALIDARG An argument was invalid.

E_POINTER An invalid pointer was specified.

E_UNEXPECTED The call was not expected (for example, the scripting engine has not yet been loadedor initialized).

pstrName[in] Address of a buffer that contains the name of the item as viewed from the script. The name mustbe unique and persistable.

dwFlags[in] Flags associated with an item. Can be a combination of these values:

10 <layout> Element

10 <layout> Element

Page 491: What is JScript?

Value Meaning

SCRIPTITEM_CODEONLY Indicates that the named item represents a code-only object, andthat the host has no IUnknown to be associated with thiscode-only object. The host only has a name for this object. Inobject-oriented languages such as C++, this flag would create aclass. Not all languages support this flag.

SCRIPTITEM_GLOBALMEMBERS Indicates that the item is a collection of global properties andmethods associated with the script. Normally, a scripting enginewould ignore the object name (other than for the purpose ofusing it as a cookie for the IActiveScriptSite::GetItemInfomethod, or for resolving explicit scoping) and expose itsmembers as global variables and methods. This allows the host toextend the library (run-time functions and so on) available to thescript. It is left to the scripting engine to deal with name conflicts(for example, when two SCRIPTITEM_GLOBALMEMBERSitems have methods of the same name), although an error shouldnot be returned because of this situation.

SCRIPTITEM_ISPERSISTENT Indicates that the item should be saved if the scripting engine issaved. Similarly, setting this flag indicates that a transition backto the initialized state should retain the item's name and typeinformation (the scripting engine must, however, release allpointers 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 themselvesobjects) can also source events to the script. This is not recursive,but it provides a convenient mechanism for the common case, forexample, of creating a container and all of its member controls.

SCRIPTITEM_ISVISIBLE Indicates that the item's name is available in the name space ofthe script, allowing access to the properties, methods, and eventsof the item. By convention the properties of the item include theitem'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 thescript's name space, and should not be treated as an item forwhich code should be associated. For example, without this flagbeing set, VBScript will create a separate module for the nameditem, and C++ might create a separate wrapper class for thenamed item.

Microsoft® Windows® Script Interfaces

IActiveScript::AddTypeLibLanguage Reference

PreviousNext

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++. Itallows a set of predefined items such as class definitions, typedefs, and named constants to be added to therun-time environment available to the script.

Returns one of the following values:

Return Value Meaning

<layout> Element 11

<layout> Element 11

Page 492: What is JScript?

S_OK Success.

E_INVALIDARG An argument was invalid.

E_UNEXPECTED The call was not expected (for example, the scripting engine has notyet been loaded or initialized).

TYPE_E_CANTLOADLIBRARY The specified type library could not be loaded.

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.

Microsoft® Windows® Script Interfaces

IActiveScript::CloneLanguage Reference

PreviousNext

HRESULT Clone( IActiveScript **ppscript // receives pointer to IActiveScript);

Clones the current scripting engine (minus any current execution state), returning a loaded scripting enginethat has no site in the current thread. The properties of this new scripting engine will be identical to theproperties the original scripting engine would be in if it were transitioned back to the initialized state.

Returns one of the following values:

Return Value Meaning

S_OK Success.

E_NOTIMPL This method is not supported.

E_POINTER An invalid pointer was specified.

E_UNEXPECTED The call was not expected (for example, the scripting engine has not yet been loadedor initialized).

ppscript[out] Address of a variable that receives a pointer to the IActiveScript interface of the cloned scriptingengine. The host must create a site and call the IActiveScript::SetScriptSite method on the newscripting engine before it will be in the initialized state and, therefore, usable.

The IActiveScript::Clone method is an optimization of IPersist*::Save, CoCreateInstance, andIPersist*::Load, so the state of the new scripting engine should be the same as if the state of the originalscripting engine were saved and loaded into a new scripting engine. Named items are duplicated in the clonedscripting engine, but specific object pointers for each item are forgotten and are obtained with theIActiveScriptSite::GetItemInfo method. This allows an identical object model with per-thread entry points (anapartment model) to be used.

12 <layout> Element

12 <layout> Element

Page 493: What is JScript?

This method is used for multithreaded server hosts that can run multiple instances of the same script. Thescripting engine may return E_NOTIMPL, in which case the host can achieve the same result by duplicatingthe 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 tothe IActiveScriptSite interface.

Microsoft® Windows® Script Interfaces

IActiveScript::CloseLanguage Reference

PreviousNext

HRESULT Close(void);

Causes the scripting engine to abandon any currently loaded script, lose its state, and release any interfacepointers it has to other objects, thus entering a closed state. Event sinks, immediately executed script text, andmacro invocations that are already in progress are completed before the state changes (useIActiveScript::InterruptScriptThread to cancel a running script thread). This method must be called by thecreating host before the interface is released to prevent circular reference problems.

Returns one of the following values:

Return Value Meaning

S_OK Success.

E_UNEXPECTED The call was not expected (for example, the scripting engine was already inthe 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 theIActiveScriptSite::OnStateChange method.

S_FALSE The method succeeded, but the script was already closed.

Microsoft® Windows® Script Interfaces

IActiveScript::GetCurrentScriptThreadIDLanguage Reference

PreviousNext

HRESULT GetCurrentScriptThreadID( SCRIPTTHREADID *pstidThread // receives scripting thread identifier);

Retrieves a scripting-engine-defined identifier for the currently executing thread. The identifier can be used insubsequent calls to script thread execution-control methods such as the IActiveScript::InterruptScriptThreadmethod.

Returns S_OK if successful, or E_POINTER if an invalid pointer was specified.•

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 theWindows thread identifier. If the Win32 thread terminates, this identifier becomes unassigned and cansubsequently 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 tothe IActiveScriptSite interface.

Microsoft® Windows® Script Interfaces Language ReferencePrevious

<layout> Element 13

<layout> Element 13

Page 494: What is JScript?

IActiveScript::GetScriptDispatch Next

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.

Returns one of the following values:

Return Value Meaning

S_OK Success.

E_INVALIDARG An argument was invalid.

E_POINTER An invalid pointer was specified.

E_UNEXPECTED The call was not expected (for example, the scripting engine has not yet been loadedor initialized).

S_FALSE The scripting engine does not support a dispatch object; the ppdisp parameter is setto NULL.

pstrItemName[in] Address of a buffer that contains the name of the item for which the caller needs the associateddispatch object. If this parameter is NULL, the dispatch object contains as its members all of theglobal methods and properties defined by the script. Through the IDispatch interface and theassociated ITypeInfo interface, the host can invoke script methods or view and modify scriptvariables.

ppdisp[out] Address of a variable that receives a pointer to the object associated with the script's globalmethods 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 IDispatchinterface returned by this method can dynamically support new methods and properties. Similarly, theIDispatch::GetTypeInfo method should return a new, unique ITypeInfo interface when methods andproperties are added. Note, however, that language engines must not change the IDispatch interface in a waythat is incompatible with any previous ITypeInfo interface returned. That implies, for example, that DISPIDswill never be reused.

Microsoft® Windows® Script Interfaces

IActiveScript::GetScriptSiteLanguage Reference

PreviousNext

HRESULT GetScriptSite( REFIID iid, // interface identifier void **ppvSiteObject // address of host site interface);

Retrieves the site object associated with the Windows Script engine.

Returns one of the following values:

Return Value Meaning

S_OK Success.

14 <layout> Element

14 <layout> Element

Page 495: What is JScript?

E_INVALIDARG An argument was invalid.

E_NOINTERFACE The specified interface is not supported.

E_POINTER An invalid pointer was specified.

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.

Microsoft® Windows® Script Interfaces

IActiveScript::GetScriptStateLanguage Reference

PreviousNext

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 withoutresulting in a non-base callout to host objects or to the IActiveScriptSite interface.

Returns S_OK if successful, or E_POINTER if an invalid pointer was specified.•

pss[out] Address of a variable that receives a value defined in the SCRIPTSTATE enumeration. Thevalue indicates the current state of the scripting engine associated with the calling thread.

Microsoft® Windows® Script Interfaces

IActiveScript::GetScriptThreadIDLanguage Reference

PreviousNext

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.

Returns one of the following values:

Return Value Meaning

S_OK Success.

E_POINTER An invalid pointer was specified.

E_UNEXPECTED The call was not expected (for example, the scripting engine has not yet been loadedor initialized) and therefore failed.

dwWin32ThreadID[in] Thread identifier of a running Win32 thread in the current process. Use theGetCurrentScriptThreadID 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 Win32thread. The interpretation of this identifier is left to the scripting engine, but it can be just a copy ofthe Windows thread identifier. Note that if the Win32 thread terminates, this identifier becomes

<layout> Element 15

<layout> Element 15

Page 496: What is JScript?

unassigned and may subsequently be assigned to another thread.

The retrieved identifier can be used in subsequent calls to script thread execution control methods such as theIActiveScript::InterruptScriptThread method.

This method can be called from non-base threads without resulting in a non-base callout to host objects or tothe IActiveScriptSite interface.

Microsoft® Windows® Script Interfaces

IActiveScript::GetScriptThreadStateLanguage Reference

PreviousNext

HRESULT GetScriptThreadState( SCRIPTTHREADID stidThread, // identifier of script thread SCRIPTTHREADSTATE *pstsState // receives state flag);

Retrieves the current state of a script thread.

Returns one of the following values:

Return Value Meaning

S_OK Success.

E_POINTER An invalid pointer was specified.

E_UNEXPECTED The call was not expected (for example, the scripting engine has not yet been loadedor initialized).

stidThread[in] Identifier of the thread for which the state is desired, or one of the following special threadidentifiers:

Value Meaning

SCRIPTTHREADID_BASE The base thread; that is, the thread in which the scripting engine wasinstantiated.

SCRIPTTHREADID_CURRENT The currently executing thread.

pstsState[out] Address of a variable that receives the state of the indicated thread. The state is indicated by oneof the named constant values defined by the SCRIPTTHREADSTATE enumeration. If this parameterdoes not identify the current thread, the state may change at any time.

This method can be called from non-base threads without resulting in a non-base callout to host objects or tothe IActiveScriptSite interface.

Microsoft® Windows® Script Interfaces

IActiveScript::InterruptScriptThreadLanguage Reference

PreviousNext

HRESULT InterruptScriptThread( SCRIPTTHREADID stidThread, // identifier of thread const EXCEPINFO *pexcepinfo, // receives error information DWORD dwFlags);

16 <layout> Element

16 <layout> Element

Page 497: What is JScript?

Interrupts the execution of a running script thread (an event sink, an immediate execution, or a macroinvocation). This method can be used to terminate a script that is stuck (in an infinite loop, for example). Itcan be called from non-base threads without resulting in a non-base callout to host objects or to theIActiveScriptSite method.

Returns one of the following values:

Return Value Meaning

S_OK Success.

E_INVALIDARG An argument was invalid.

E_POINTER An invalid pointer was specified.

E_UNEXPECTED The call was not expected (for example, the scripting engine has not yet been loadedor initialized).

stidThread[in] Identifier of the thread to interrupt, or one of the following special thread identifier values:

Value Meaning

SCRIPTTHREADID_ALL All threads. The interrupt is applied to all scriptmethods currently in progress. Note that unless thecaller has requested that the script be disconnected,by calling the IActiveScript::SetScriptState methodwith the SCRIPTSTATE_DISCONNECTED orSCRIPTSTATE_INITIALIZED flag set, the nextscripted event causes script code to run again.

SCRIPTTHREADID_BASE The base thread; that is, the thread in which thescripting engine was instantiated.

SCRIPTTHREADID_CURRENT The currently executing thread.

pexcepinfo[in] Address of an EXCEPINFO structure that receives error information associated with the errorcondition.

dwFlags[in] Option flags associated with the interruption. Can be one of these values:

Value Meaning

SCRIPTINTERRUPT_DEBUG If supported, enter the scripting engine's debugger at thecurrent script execution point.

SCRIPTINTERRUPT_RAISEEXCEPTION If supported by the scripting engine's language, let thescript handle the exception. Otherwise, the script method isaborted and the error code is returned to the caller; that is,the event source or macro invoker.

Microsoft® Windows® Script Interfaces

IActiveScript::SetScriptSiteLanguage Reference

PreviousNext

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 becalled before any other IActiveScript interface methods can be used.

<layout> Element 17

<layout> Element 17

Page 498: What is JScript?

Returns one of the following values:

Return Value Meaning

S_OK Success.

E_FAIL An unspecified error occurred; the scripting engine was unable to finish initializingthe site.

E_INVALIDARG An argument was invalid.

E_POINTER An invalid pointer was specified.

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 otherscripting engines.

Microsoft® Windows® Script Interfaces

IActiveScript::SetScriptStateLanguage Reference

PreviousNext

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 withoutresulting in a non-base callout to host objects or to the IActiveScriptSite interface.

Returns one of the following values:Return Value Meaning

S_OK Success.

E_FAIL The scripting engine does not support the transition back to the initializedstate. The host must discard this scripting engine and create, initialize, andload a new scripting engine to achieve the same effect.

E_UNEXPECTED The call was not expected (for example, the scripting engine has not yetbeen 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 theIActiveScriptSite::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 theSCRIPTSTATE enumeration.

For more information about scripting engine states, see Script Engine States.

See also IActiveScript::Clone, IActiveScript::GetScriptDispatch, IActiveScript::InterruptScriptThread,IActiveScriptParse::ParseScriptText, IActiveScriptSite::GetItemInfo

Microsoft® Windows® Script Interfaces

IActiveScriptErrorLanguage Reference

PreviousNext

18 <layout> Element

18 <layout> Element

Page 499: What is JScript?

An object implementing this interface is passed to the IActiveScriptSite::OnScriptErrormethod whenever the scripting engine encounters an unhandled error. The host then callsmethods on this object to obtain information about the error that occurred.

Methods in Vtable Order

Method Description

GetExceptionInfo Retrieves information about an error.

GetSourcePosition Retrieves the location in the source code where an error occurred.

GetSourceLineText Retrieves the line in the source file where an error occurred.

Microsoft® Windows® Script Interfaces

IActiveScriptError::GetExceptionInfoLanguage Reference

PreviousNext

HRESULT GetExceptionInfo( EXCEPINFO *pexcepinfo // structure for exception information);

Retrieves information about an error that occurred while the scripting engine was running a script.

Returns S_OK if successful, or E_FAIL if an error occurred.•

pexcepinfo[out] Address of an EXCEPINFO structure that receives error information.

Microsoft® Windows® Script Interfaces

IActiveScriptError::GetSourceLineTextLanguage Reference

PreviousNext

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.

Microsoft® Windows® Script Interfaces

IActiveScriptError::GetSourcePositionLanguage Reference

PreviousNext

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

<layout> Element 19

<layout> Element 19

Page 500: What is JScript?

Returns S_OK if successful, or E_FAIL if the location was not retrieved.•

pdwSourceContext[out] Address of a variable that receives a cookie that identifies the context. The interpretation of thisparameter 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.

Microsoft® Windows® Script Interfaces

IActiveScriptParseLanguage Reference

PreviousNext

If the Windows Script engine allows raw text code scriptlets to be added to the script orallows expression text to be evaluated at run time, it implements the IActiveScriptParseinterface. For interpreted scripting languages that have no independent authoringenvironment, 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 objectevents.

Methods in Vtable Order

Method Description

InitNew Initializes the scripting engine.

AddScriptlet Adds a code scriptlet to the script.

ParseScriptText Parses the given code scriptlet, adding declarations into the namespace and evaluating code as appropriate.

Microsoft® Windows® Script Interfaces

IActiveScriptParse::AddScriptletLanguage Reference

PreviousNext

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 scriptis intertwined with the host document and the host is responsible for restoring the script, rather than throughan IPersist* interface. The primary examples are HTML scripting languages that allow scriptlets of codeembedded in the HTML document to be attached to intrinsic events (for instance,ONCLICK="button1.text='Exit'").

Returns one of the following values:•

20 <layout> Element

20 <layout> Element

Page 501: What is JScript?

Return Value Meaning

S_OK Success.

DISP_E_EXCEPTION An exception occurred in the parsing of the scriptlet; the pexcepinfoparameter contains information about the exception.

E_INVALIDARG An argument was invalid.

E_NOTIMPL This method is not supported; the scripting engine does not supportadding event-sinking scriptlets.

E_POINTER An invalid pointer was specified.

E_UNEXPECTED The call was not expected (for example, the scripting engine has notyet been loaded or initialized) and therefore failed.

OLESCRIPT_E_INVALIDNAME The default name supplied is invalid in this scripting language.

OLESCRIPT_E_SYNTAX An unspecified syntax error occurred in the scriptlet.

pstrDefaultName[in] Address of a default name to associate with the scriptlet. If the scriptlet does not contain naminginformation (as in the ONCLICK example above), this name will be used to identify the scriptlet. Ifthis 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 scriptinglanguage.

pstrItemName[in] Address of a buffer that contains the item name associated with this scriptlet. This parameter, inaddition 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 thisscriptlet is associated; this name must be found in the named item's type information. This parameteris 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 oftext, the host typically uses a delimiter, such as two single quotation marks ("), to detect the end of thescriptlet. This parameter specifies the delimiter that the host used, allowing the scripting engine toprovide 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 enginemakes use of this information depends on the scripting engine. Set this parameter to NULL if the hostdid 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:

Return Value Meaning

SCRIPTTEXT_ISVISIBLE Indicates that the script text should be visible (and, therefore,callable by name) as a global method in the name space of thescript.

SCRIPTTEXT_ISPERSISTENT

<layout> Element 21

<layout> Element 21

Page 502: What is JScript?

Indicates that the code added during this call should be savedif the scripting engine is saved (for example, through a call toIPersist*::Save), or if the scripting engine is reset by way ofa transition back to the initialized state. For more informationabout this state, see Script Engine States.

pbstrName[out] Actual name used to identify the scriptlet. This will be, in order of preference: a name explicitlyspecified in the scriptlet text, the default name provided in pstrDefaultName, or a unique namesynthesized by the scripting engine.

pexcepinfo[out] Address of a structure containing exception information. This structure should be filled in ifDISP_E_EXCEPTION is returned.

Microsoft® Windows® Script Interfaces

IActiveScriptParse::InitNewLanguage Reference

PreviousNext

HRESULT InitNew(void);

Initializes the scripting engine.

Returns S_OK if successful, or E_FAIL if an error occurred during initialization.•

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 toIPersistStreamInit::InitNew, in that this method tells the scripting engine to initialize itself. Note that it isnot valid to call both IPersist*::InitNew or IActiveScriptParse::InitNew and IPersist*::Load, nor is itvalid to call IPersist*::InitNew, IActiveScriptParse::InitNew, or IPersist*::Load more than once.

Microsoft® Windows® Script Interfaces

IActiveScriptParse::ParseScriptTextLanguage Reference

PreviousNext

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.

Returns one of the following values:

Return Value Meaning

S_OK Success.

DISP_E_EXCEPTION An exception occurred in the processing of the scriptlet. The pexcepinfoparameter contains information about the exception.

E_INVALIDARG An argument was invalid.

22 <layout> Element

22 <layout> Element

Page 503: What is JScript?

E_POINTER An invalid pointer was specified.

E_NOTIMPL This method is not supported. The scripting engine does not supportrun-time evaluation of expressions or statements.

E_UNEXPECTED The call was not expected (for example, the scripting engine is in theuninitialized or closed state, or the SCRIPTTEXT_ISEXPRESSION flagwas set and the scripting engine is in the initialized state).

OLESCRIPT_E_SYNTAX An unspecified syntax error occurred in the scriptlet.

pstrCode[in] Address of the scriptlet text to evaluate. The interpretation of this string depends on the scriptinglanguage.

pstrItemName[in] Address of the item name that gives the context in which the scriptlet is to be evaluated. If thisparameter 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, wheresuch a context may be provided by the debugger to represent an active run-time context. If thisparameter 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 hosttypically 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 providesome conditional primitive preprocessing (for example, replacing a single quotation mark ['] with twosingle quotation marks for use as a delimiter). Exactly how (and if) the scripting engine makes use ofthis information depends on the scripting engine. Set this parameter to NULL if the host did not use adelimiter 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_ISEXPRESSION If the distinction between a computational expression and a statementis important but syntactically ambiguous in the script language, thisflag specifies that the scriptlet is to be interpreted as an expression,rather than as a statement or list of statements. By default, statementsare assumed unless the correct choice can be determined from thesyntax of the scriptlet text.

SCRIPTTEXT_ISPERSISTENT Indicates that the code added during this call should be saved if thescripting engine is saved (for example, through a call toIPersist*::Save), or if the scripting engine is reset by way of atransition back to the initialized state.

SCRIPTTEXT_ISVISIBLE Indicates that the script text should be visible (and, therefore, callableby 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 expectsno result (that is, the SCRIPTTEXT_ISEXPRESSION value is not set).

pexcepinfo[out] Address of a structure that receives exception information. This structure is filled ifIActiveScriptParse::ParseScriptText returns DISP_E_EXCEPTION.

<layout> Element 23

<layout> Element 23

Page 504: What is JScript?

If the scripting engine is in the initialized state, no code will actually be evaluated during this call; rather, suchcode 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 theSCRIPTTEXT_ISEXPRESSION flag when in the initialized state.

The scriptlet can be an expression, a list of statements, or anything allowed by the script language. Forexample, this method is used in the evaluation of the HTML <SCRIPT> tag, which allows statements to beexecuted 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 isillegal to call this method once with Sub Function(x) and then a second time with End Sub. The parser mustnot wait for the second call to complete the subroutine, but rather must generate a parse error because asubroutine declaration was started but not completed.

For more information about script states, see Script Engine States.

Microsoft® Windows® Script Interfaces

IActiveScriptSiteLanguage Reference

PreviousNext

The host must create a site for the Windows Script engine by implementing theIActiveScriptSite interface. Usually, this site will be associated with the container of all theobjects that are visible to the script (for example, the ActiveX Controls). Typically, thiscontainer 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. EachActiveX control (or other automation object) on the page, and the scripting engine itself,would be enumerable within this container.

Methods in Vtable Order

Method Description

GetLCID Retrieves the locale identifier that the host uses for displayinguser-interface elements.

GetItemInfo Obtains information about an item that was added to an enginethrough a call to the IActiveScript::AddNamedItem method.

GetDocVersionString Retrieves a host-defined string that uniquely identifies thecurrent document version from the host's point of view.

OnScriptTerminate Called when the script has completed execution.

OnStateChange Informs the host that the scripting engine has changed states.

OnScriptError Informs the host that an execution error occurred while theengine was running the script.

OnEnterScript Informs the host that the scripting engine has begun executingthe script code.

OnLeaveScript Informs the host that the scripting engine has returned fromexecuting script code.

Microsoft® Windows® Script Interfaces

IActiveScriptSite::GetDocVersionStringLanguage Reference

PreviousNext

HRESULT GetDocVersionString( BSTR *pbstrVersionString // address of document version string);

24 <layout> Element

24 <layout> Element

Page 505: What is JScript?

Retrieves a host-defined string that uniquely identifies the current document version. If the related documenthas changed outside the scope of Windows Script (as in the case of an HTML page being edited withNotePad), the scripting engine can save this along with its persisted state, forcing a recompile the next timethe script is loaded.

Returns S_OK if successful, or E_NOTIMPL if this method is not supported.•

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.

Microsoft® Windows® Script Interfaces

IActiveScriptSite::GetItemInfoLanguage Reference

PreviousNext

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::AddNamedItemmethod.

Returns one of the following values:

Return Value Meaning

S_OK Success.

E_INVALIDARG An argument was invalid.

E_POINTER An invalid pointer was specified.

TYPE_E_ELEMENTNOTFOUND An item of the specified name was not found.

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 engineshould 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 thefollowing values:

Value Meaning

SCRIPTINFO_IUNKNOWN Return the IUnknown interface for this item.

SCRIPTINFO_ITYPEINFO Return the ITypeInfo interface for this item.

ppunkItem[out] Address of a variable that receives a pointer to the IUnknown interface associated with thegiven item. The scripting engine can use the IUnknown::QueryInterface method to obtain theIDispatch interface for the item. This parameter receives NULL if dwReturnMask does not includethe SCRIPTINFO_IUNKNOWN value. Also, it receives NULL if there is no object associated withthe item name; this mechanism is used to create a simple class when the named item was added withthe SCRIPTITEM_CODEONLY flag set in the IActiveScript::AddNamedItem method.

<layout> Element 25

<layout> Element 25

Page 506: What is JScript?

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_ITYPEINFOvalue, or if type information is not available for this item. If type information is not available, theobject cannot source events, and name binding must be realized with theIDispatch::GetIDsOfNames method. Note that the ITypeInfo interface retrieved describes the item'scoclass (TKIND_COCLASS) because the object may support multiple interfaces and event interfaces.If the item supports the IProvideMultipleTypeInfo interface, the ITypeInfo interface retrieved is thesame as the index zero ITypeInfo that would be obtained using theIProvideMultipleTypeInfo::GetInfoOfIndex method.

This method retrieves only the information indicated by the dwReturnMask parameter; this improvesperformance. For example, if an ITypeInfo interface is not needed for an item, it is simply not specified indwReturnMask.

Microsoft® Windows® Script Interfaces

IActiveScriptSite::GetLCIDLanguage Reference

PreviousNext

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 identifierto ensure that error strings and other user-interface elements generated by the engine appear in the appropriatelanguage.

Returns one of the following values:

Return Value Meaning

S_OK Success.

E_NOTIMPL This method is not implemented. Use the system-defined locale.

E_POINTER An invalid pointer was specified.

plcid[out] Address of a variable that receives the locale identifier for user-interface elements displayed bythe scripting engine.

If this method returns E_NOTIMPL, the system-defined locale identifier should be used.

Microsoft® Windows® Script Interfaces

IActiveScriptSite::OnEnterScriptLanguage Reference

PreviousNext

HRESULT OnEnterScript(void);

Informs the host that the scripting engine has begun executing the script code.

Returns S_OK if successful.•

The scripting engine must call this method on every entry or reentry into the scripting engine. For example, ifthe script calls an object that then fires an event handled by the scripting engine, the scripting engine must callIActiveScriptSite::OnEnterScript before executing the event, and must call theIActiveScriptSite::OnLeaveScript method after executing the event but before returning to the object that fired

26 <layout> Element

26 <layout> Element

Page 507: What is JScript?

the event. Calls to this method can be nested. Every call to this method requires a corresponding call toIActiveScriptSite::OnLeaveScript.

Microsoft® Windows® Script Interfaces

IActiveScriptSite::OnLeaveScriptLanguage Reference

PreviousNext

HRESULT IActiveScriptSite::OnLeaveScript(void);

Informs the host that the scripting engine has returned from executing script code.

Returns S_OK if successful.•

The scripting engine must call this method before returning control to a calling application that entered thescripting engine. For example, if the script calls an object that then fires an event handled by the scriptingengine, 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 thatfired the event. Calls to this method can be nested. Every call to IActiveScriptSite::OnEnterScript requiresa corresponding call to this method.

Microsoft® Windows® Script Interfaces

IActiveScriptSite::OnScriptErrorLanguage Reference

PreviousNext

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 obtaininformation about the execution error.

Microsoft® Windows® Script Interfaces

IActiveScriptSite::OnScriptTerminateLanguage Reference

PreviousNext

HRESULT OnScriptTerminate( VARIANT *pvarResult, // address of script results EXCEPINFO *pexcepinfo // address of structure with exception information);

Informs the host that the script has completed execution.

Returns S_OK if successful.•

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 thescript terminated, or NULL if no exception was generated.

The scripting engine calls this method before the call to the IActiveScriptSite::OnStateChange method, withthe SCRIPTSTATE_INITIALIZED flag set, is completed. This method can be used to return completion

<layout> Element 27

<layout> Element 27

Page 508: What is JScript?

status and results to the host. Note that many script languages, which are based on sinking events from thehost, have life spans that are defined by the host. In this case, this method may never be called.

Microsoft® Windows® Script Interfaces

IActiveScriptSite::OnStateChangeLanguage Reference

PreviousNext

HRESULT IActiveScriptSite::OnStateChange( SCRIPTSTATE ssScriptState // new state of engine);

Informs the host that the scripting engine has changed states.

Returns S_OK if successful.•

ssScriptState[in] Value that indicates the new script state. See the IActiveScript::GetScriptState method for adescription of the states.

Microsoft® Windows® Script Interfaces

IActiveScriptSiteWindowLanguage Reference

PreviousNext

This interface is implemented by hosts that support a user interface on the same object asIActiveScriptSite. Hosts that do not support a user interface, such as servers, would notimplement the IActiveScriptSiteWindow interface. The scripting engine accesses thisinterface by calling QueryInterface from IActiveScriptSite.

Methods in Vtable Order

Method Description

GetWindow Retrieves the window handle that can act as the owner of apop-up window that the scripting engine must display.

EnableModeless Causes the host to enable or disable its main window as wellas any modeless dialog boxes.

Microsoft® Windows® Script Interfaces

IActiveScriptSiteWindow::EnableModelessLanguage Reference

PreviousNext

HRESULT IActiveScriptSite::EnableModeless( BOOL fEnable // enable flag);

Causes the host to enable or disable its main window as well as any modeless dialog boxes.

Returns S_OK if successful, or E_FAIL if an error occurred.•

fEnable[in] Flag that, if TRUE, enables the main window and modeless dialogs or, if FALSE, disables them.

This method is identical to the IOleInPlaceFrame::EnableModeless method.

Calls to this method can be nested.

28 <layout> Element

28 <layout> Element

Page 509: What is JScript?

Microsoft® Windows® Script Interfaces

IActiveScriptSiteWindow::GetWindowLanguage Reference

PreviousNext

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

Returns S_OK if successful, or E_FAIL if an error occurred.•

phwnd[out] Address of a variable that receives the window handle.

This method is similar to the IOleWindow::GetWindow method.

Microsoft® Windows® Script Interfaces

EnumerationsLanguage Reference

PreviousNext

This section describes the enumerations used by Windows Script engines.

SCRIPTSTATE♦ SCRIPTTHREADSTATE♦

Microsoft® Windows® Script Interfaces

SCRIPTSTATELanguage Reference

PreviousNext

typedef enum tagSCRIPTSTATE { SCRIPTSTATE_UNINITIALIZED = 0, SCRIPTSTATE_INITIALIZED = 5, SCRIPTSTATE_STARTED = 1, SCRIPTSTATE_CONNECTED = 2, SCRIPTSTATE_DISCONNECTED = 3, SCRIPTSTATE_CLOSED = 4} SCRIPTSTATE;

Contains named constant values that specify the state of a scripting engine. This enumeration is used by theIActiveScript::GetScriptState, IActiveScript::SetScriptState, and IActiveScriptSite::OnStateChange methods.

SCRIPTSTATE_UNINITIALIZEDScript has just been created, but has not yet been initialized using an IPersist* interface andIActiveScript::SetScriptSite.

SCRIPTSTATE_INITIALIZEDScript has been initialized, but is not running (connecting to other objects or sinking events) orexecuting any code. Code can be queried for execution by calling theIActiveScriptParse::ParseScriptText method.

SCRIPTSTATE_STARTEDScript can execute code, but is not yet sinking the events of objects added by theIActiveScript::AddNamedItem method.

SCRIPTSTATE_CONNECTEDScript is loaded and connected for sinking events.

SCRIPTSTATE_DISCONNECTEDScript is loaded and has a run-time execution state, but is temporarily disconnected from sinkingevents.

<layout> Element 29

<layout> Element 29

Page 510: What is JScript?

SCRIPTSTATE_CLOSEDScript has been closed. The scripting engine no longer works and returns errors for most methods.

30 <layout> Element

30 <layout> Element