What is JScript?
Short Description
Download What is JScript?...
Description
What Is JScript?
What Is JScript?
Table of Contents What Is JScript?.................................................................................................................................................1 Using JScript............................................................................................................................................1 Writing JScript Code..........................................................................................................................................1 Statements................................................................................................................................................1 Comments................................................................................................................................................1 Assignments and Equality.......................................................................................................................2 Expressions..............................................................................................................................................2 JScript Variables.................................................................................................................................................1 Declaring Variables.................................................................................................................................1 Naming Variables....................................................................................................................................1 Coercion...................................................................................................................................................2 JScript Data Types..............................................................................................................................................1 String Data Type......................................................................................................................................1 Number Data Type...................................................................................................................................1 Integer Values....................................................................................................................................1 Floating-point Values........................................................................................................................2 Boolean Data Type..................................................................................................................................2 Null Data Type.........................................................................................................................................3 Undefined Data Type...............................................................................................................................3 JScript Operators................................................................................................................................................1 Computational Operators.........................................................................................................................1 Logical Operators..............................................................................................................................1 Controlling Program Flow.................................................................................................................................1 Using Conditional Statements.................................................................................................................1 Conditional Operator...............................................................................................................................2 Using Loops.............................................................................................................................................2 Using for Loops.......................................................................................................................................3 Using for...in Loops.................................................................................................................................3 Using while Loops...................................................................................................................................4 Using break and continue Statements......................................................................................................4 JScript Objects....................................................................................................................................................1 Objects as Arrays.....................................................................................................................................1 JScript Reserved Words.....................................................................................................................................1 Future Reserved Words............................................................................................................................1 Advanced Object Creation.................................................................................................................................1 Writing Constructors................................................................................................................................1 Using Prototypes to Create Objects.........................................................................................................1 Recursion.............................................................................................................................................................1 Variable Scope.....................................................................................................................................................1
i
What Is JScript?
Table of Contents Copying, Passing, and Comparing Data...........................................................................................................1 By Value vs. By Reference......................................................................................................................1 Passing Parameters to Functions..............................................................................................................1 Testing Data.............................................................................................................................................2 Special Characters..............................................................................................................................................1 Troubleshooting Your Scripts...........................................................................................................................1 Syntax Errors...........................................................................................................................................1 Order of Script Interpretation...................................................................................................................1 Automatic Type Coercion........................................................................................................................1 Operator Precedence................................................................................................................................1 Using for...in Loops with Objects............................................................................................................1 with Keyword...........................................................................................................................................2 this Keyword............................................................................................................................................2 Writing a Script That Writes a Script in Internet Explorer......................................................................2 Implicit Window References in Internet Explorer...................................................................................2 Microsoft JScript Features - ECMA.................................................................................................................1 Microsoft JScript Features - Non-ECMA.........................................................................................................1 abs Method..........................................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 acos Method.........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 anchor Method....................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 asin Method.........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 atan Method.........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 atan2 Method.......................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 big Method...........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1
ii
What Is JScript?
Table of Contents blink Method.......................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 bold Method.........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 ceil Method..........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 charAt Method....................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 compile Method...................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 concat Method (Array).......................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 concat Method (String).......................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 cos Method...........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 dimensions Method.............................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................2 escape Method.....................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 eval Method.........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 exec Method.........................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 exp Method..........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1
iii
What Is JScript?
Table of Contents fixed Method........................................................................................................................................................1 The required strVariable reference is any String object or literal............................................................1 Remarks.............................................................................................................................................1 floor Method........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 fontcolor Method.................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 fontsize Method...................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 getDate Method...................................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 getDay Method....................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 getHours Method................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 getMinutes Method.............................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 getMonth Method................................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 getSeconds Method.............................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 getTime Method..................................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 getTimezoneOffset Method................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 getVarDate Method............................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1
iv
What Is JScript?
Table of Contents getYear Method...................................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 indexOf Method..................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 italics Method......................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 item Method.........................................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 join Method..........................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 lastIndexOf Method............................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 lbound Method....................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 link Method..........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 log Method...........................................................................................................................................................1 Return Value............................................................................................................................................1 Requirements.....................................................................................................................................1 match Method......................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 max Method.........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 min Method..........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 parse Method.......................................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1
v
What Is JScript?
Table of Contents parseFloat Method..............................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 parseInt Method..................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 pow Method.........................................................................................................................................................1 Arguments................................................................................................................................................1 Example.............................................................................................................................................1 random Method...................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 replace Method....................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 reverse Method....................................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 round Method......................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 search Method.....................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 setDate Method....................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 setHours Method.................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 setMonth Method................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 setSeconds Method..............................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 setTime Method...................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1
vi
What Is JScript?
Table of Contents setYear Method...................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 sin Method...........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 slice Method (Array)...........................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 slice Method (String)...........................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 small Method.......................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 sort Method..........................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 split Method.........................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 sqrt Method.........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 strike Method......................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 sub Method..........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 substr Method......................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 substring Method................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 sup Method..........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1
vii
What Is JScript?
Table of Contents tan Method...........................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 test Method..........................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 toGMTString Method.........................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 toLocaleString Method.......................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 toLowerCase Method..........................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 toUpperCase Method..........................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 ubound Method...................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 unescape Method.................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 Array Object........................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 arguments Object................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Date Object..........................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Global Object......................................................................................................................................................1 Remarks...................................................................................................................................................1 Properties...........................................................................................................................................1 Math Object.........................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1
viii
What Is JScript?
Table of Contents Regular Expression Object................................................................................................................................1 Syntax 1...................................................................................................................................................1 Syntax 2.............................................................................................................................................1 String Object.......................................................................................................................................................1 Syntax......................................................................................................................................................1 Arguments.........................................................................................................................................1 Addition Assignment Operator (+=).................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Bitwise AND Assignment Operator (&=).........................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Bitwise AND Operator (&)................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Bitwise Left Shift Operator ().....................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Bitwise XOR Assignment Operator (^=)..........................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Bitwise XOR Operator (^).................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Comma Operator (,)...........................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1
ix
What Is JScript?
Table of Contents Comparison Operators.......................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Conditional (Ternary) Operator (?:)................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 delete Operator....................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 Division Assignment Operator (/=)....................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Increment (++) and Decrement ( ) Operators...............................................................................................1 Syntax 1...................................................................................................................................................1 Syntax 2.............................................................................................................................................1 instanceof Operator............................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Left Shift Assignment Operator (=)...........................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1
x
What Is JScript?
Table of Contents Subtraction Assignment Operator (-=).............................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 typeof Operator...................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 Unsigned Right Shift Operator (>>>)...............................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Unsigned Right Shift Assignment Operator (>>>=)........................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 void Operator......................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 0...n Properties.....................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 $1...$9 Properties.................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 callee Property.....................................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 constructor Property..........................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 E Property............................................................................................................................................................1 Requirements...........................................................................................................................................1 See Also.............................................................................................................................................1 index Property.....................................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 input Property ($_).............................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 length Property (arguments)..............................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1
xi
What Is JScript?
Table of Contents length Property (Array).....................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 length Property (Function).................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 length Property (String).....................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 LN10 Property.....................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 LN2 Property.......................................................................................................................................................1 Syntax......................................................................................................................................................1 Requirements.....................................................................................................................................1 LOG10E Property...............................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 LOG2E Property.................................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 PI Property..........................................................................................................................................................1 Syntax......................................................................................................................................................1 Requirements.....................................................................................................................................1 prototype Property..............................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 source Property...................................................................................................................................................1 Requirements...........................................................................................................................................1 See Also.............................................................................................................................................1 SQRT1_2 Property.............................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 SQRT2 Property.................................................................................................................................................1 Syntax......................................................................................................................................................1 Requirements.....................................................................................................................................1 undefined Property.............................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1
xii
What Is JScript?
Table of Contents @cc_on Statement...............................................................................................................................................1 Remarks...................................................................................................................................................1 Requirements.....................................................................................................................................1 @if Statement......................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 @set Statement....................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 break Statement..................................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 Comment Statements..........................................................................................................................................1 Syntax 1...................................................................................................................................................1 Syntax 2.............................................................................................................................................1 continue Statement..............................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 do...while Statement............................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 for Statement.......................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 for...in Statement.................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 function Statement..............................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 if...else Statement.................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Labeled Statement..............................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 return Statement.................................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1
xiii
What Is JScript?
Table of Contents switch Statement.................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 this Statement......................................................................................................................................................1 Remarks...................................................................................................................................................1 Example.............................................................................................................................................1 try...catch
finally Statement..............................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 var Statement......................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 while Statement...................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 with Statement.....................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 VBScript User's Guide.......................................................................................................................................1 Adding VBScript Code to an HTML Page.......................................................................................................1 The Tag.................................................................................................................................1 A Simple VBScript Page.....................................................................................................................................1 A Simple Page.........................................................................................................................................1 Other Ways to Attach Code to Events...............................................................................................1 VBScript and Forms...........................................................................................................................................1 Simple Validation....................................................................................................................................1 Using Numeric Values......................................................................................................................1 Using VBScript with Objects.............................................................................................................................1 Using Objects...........................................................................................................................................1 VBScript Language Reference...........................................................................................................................1 Count Property....................................................................................................................................................1 Remarks...................................................................................................................................................1 See Also.............................................................................................................................................1 Item Property......................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1
xiv
What Is JScript?
Table of Contents Key Property.......................................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Add Method (Dictionary)...................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Column Property................................................................................................................................................1 Remarks...................................................................................................................................................1 See Also.............................................................................................................................................1 Line Property......................................................................................................................................................1 Remarks...................................................................................................................................................1 See Also.............................................................................................................................................1 Add Method (Folders)........................................................................................................................................1 Arguments................................................................................................................................................1 Remarks.............................................................................................................................................1 Count Property....................................................................................................................................................1 Remarks...................................................................................................................................................1 See Also.............................................................................................................................................1 Script Components..............................................................................................................................................1 Script Components Overview............................................................................................................................1 Introducing Windows Script Components.......................................................................................................1 See Also...................................................................................................................................................1 How Script Components Work..........................................................................................................................1 See Also...................................................................................................................................................1 Script Component File Contents.......................................................................................................................1 Skeleton Script Component File..............................................................................................................2 See Also.............................................................................................................................................3 Using the Script Component Wizard................................................................................................................1 See Also...................................................................................................................................................1 Creating Registration Information...................................................................................................................1 Running Script During Registration........................................................................................................2 Registering for Remote Access................................................................................................................2 See Also.............................................................................................................................................3 Exposing Methods...............................................................................................................................................1 See Also...................................................................................................................................................2 Exposing Properties............................................................................................................................................1 See Also...................................................................................................................................................3
xv
What Is JScript?
Table of Contents Exposing Events..................................................................................................................................................1 Declaring Events......................................................................................................................................1 Specifying Dispatch Identifiers................................................................................................................1 Firing an Event.........................................................................................................................................2 See Also.............................................................................................................................................2 Creating a Script Component Type Library....................................................................................................1 Generating Type Libraries Dynamically.................................................................................................1 Command-line Interface..........................................................................................................................2 Troubleshooting Type Libraries..............................................................................................................3 See Also.............................................................................................................................................3 Referencing Other Components........................................................................................................................1 Referencing Additional COM Components.............................................................................................1 Referencing an External Type Library....................................................................................................1 Referencing Resources.............................................................................................................................1 See Also.............................................................................................................................................2 Referencing Another Script Component in the Same Package......................................................................1 See Also...................................................................................................................................................2 Checking For Errors in Script Component Files.............................................................................................1 Setting Error Options...............................................................................................................................1 See Also.............................................................................................................................................1 Using a Script Component in an Application...................................................................................................1 Creating Local Instances of Script Components......................................................................................1 Creating Remote Instances of Script Components..................................................................................2 See Also.............................................................................................................................................3 Handling Script Component Events in the Host Application.........................................................................1 See Also...................................................................................................................................................1 Creating a Behavior Script Component...........................................................................................................1 Creating a Behavior Script Component File............................................................................................1 Behavior-Related Enhancements to the DHTML Object Model.............................................................2 Getting Event Parameters in the Script Component................................................................................3 Scope Rules..............................................................................................................................................3 Timing Considerations.............................................................................................................................4 See Also.............................................................................................................................................4 Exposing Properties and Methods in Behavior Script Components..............................................................1 Exposing a Property.................................................................................................................................1 Exposing a Method..................................................................................................................................1 See Also.............................................................................................................................................1 Exposing Custom Events in Behavior Script Components.............................................................................1 Getting and Setting Custom Event Information......................................................................................1 Example...................................................................................................................................................1 See Also.............................................................................................................................................2
xvi
What Is JScript?
Table of Contents Element.......................................................................................................................................1 Values......................................................................................................................................................1 Remarks.............................................................................................................................................1 Element............................................................................................................................................1 Values......................................................................................................................................................1 Remarks.............................................................................................................................................1 Element................................................................................................................................................1 See Also...................................................................................................................................................1 Element...........................................................................................................................................1 Values......................................................................................................................................................1 Remarks.............................................................................................................................................1 Element.......................................................................................................................................1 Values......................................................................................................................................................1 Remarks.............................................................................................................................................1 Element............................................................................................................................................1 Values......................................................................................................................................................1 Remarks.............................................................................................................................................1 Element.................................................................................................................................................1 Values......................................................................................................................................................1 Remarks.............................................................................................................................................1 Element........................................................................................................................................1 Values......................................................................................................................................................1 Remarks.............................................................................................................................................1 Element................................................................................................................................................1 Values......................................................................................................................................................1 Example.............................................................................................................................................1 element Property.................................................................................................................................................1 Values......................................................................................................................................................1 Remarks.............................................................................................................................................1 Element................................................................................................................................................1 Values......................................................................................................................................................1 Remarks.............................................................................................................................................1
xvii
What Is JScript?
xviii
What Is JScript? JScript is the Microsoft implementation of the ECMA 262 language specification (ECMAScript Edition 3). With only a few minor exceptions (to maintain backwards compatibility), JScript is a full implementation of the ECMA standard. This overview is intended to help you get started with JScript.
Using JScript JScript is an interpreted, object-based scripting language. Although it has fewer capabilities than full-fledged object-oriented languages like C++, JScript is more than sufficiently powerful for its intended purposes. JScript is not a cut-down version of another language (it is only distantly and indirectly related to Java, for example), nor is it a simplification of anything. It is, however, limited. You cannot write stand-alone applications in it, for example, and it has no built-in support for reading or writing files. Moreover, JScript scripts can run only in the presence of an interpreter or "host", such as Active Server Pages (ASP), Internet Explorer, or Windows Script Host. JScript is a loosely typed language. Loosely typed means you do not have to declare the data types of variables explicitly. In fact, JScript takes it one step further. You cannot explicitly declare data types in JScript. Moreover, in many cases JScript performs conversions automatically when needed. For instance, if you add a number to an item consisting of text (a string), the number is converted to text. The rest of this user's guide is an overview of JScript features. For full details of the language implementation, consult the language reference. Note The code in many of the following examples is somewhat more explicit and less dense than code you are likely to find in actual Web pages. The intent here is to clarify the concepts, not to express optimal coding conciseness and style. In any case, there is no shame in writing code that you can read and easily understand six months after you write it.
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
What Is JScript?
1
2
What Is JScript?
2
What Is JScript?
Writing JScript Code Like many other programming languages, Microsoft JScript is written in text format, and organized into statements, blocks consisting of related sets of statements, and comments. Within a statement you can use variables, immediate data such as strings and numbers (called "literals"), and expressions.
Statements A JScript program is a collection of statements. A JScript statement is equivalent to a complete sentence in English. JScript statements combine expressions in such a way that they carry out one complete task. A statement consists of one or more expressions, keywords, or operators (symbols). Typically, a statement is written on a single line, although a statement can be written over two or more lines. Also, two or more statements can be written on the same line by separating them with semicolons. In general, each new line begins a new statement. It is a good idea to terminate your statements explicitly. You do this with the semicolon (;), which is the JScript statement termination character. Here are two examples of JScript statements. aBird = "Robin"; // Assign the text "Robin" to the variable aBird var 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 block can generally be treated as a single statement. This means you can use blocks in most places that JScript expects a lone statement. Notable exceptions include the headers of for and while loops. Notice that the primitive statements within a block end in semicolons, but the block itself does not. Generally, blocks are used in functions and conditionals. Notice that unlike C++ and some other languages, JScript does not consider a block to be a new scope; only functions create a new scope. In the following example, the first statement begins the definition of a function that consists of a block of five statements. Following the block are three statements that are not surrounded by braces; these statements are not a block, and are therefore not part of the function definition. function convert(inches) { feet = inches / 12; // These five statements are in a block. miles = feet / 5280; nauticalMiles = feet / 6080; cm = inches * 2.54; meters = inches / 39.37; } km = meters / 1000; // These three statements are not in a block. kradius = km; mradius = miles;
Comments A single-line JScript comment begins with a pair of forward slashes (//). Here is an example of a single line comment. 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
2
Writing JScript Code
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 the resulting multiline comment in an unexpected way. The */ that marks the end of the embedded multiline comment is interpreted as the end of the whole multiline comment. This means that the text that follows the embedded multiline comment will not be commented out; instead, it will be interpreted as JScript code, and will generate syntax errors. It is recommended that you write all your comments as blocks of single-line comments. This allows you to comment out large segments of code with a multiline comment later. // // // //
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. The left 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 is discussed in detail in Controlling Program Flow.
Expressions A JScript expression is a 'phrase' of JScript that a JScript interpreter can evaluate to generate a value. The value can be of any valid JScript type - a number, a string, an object, and so on. The simplest expressions are literals. Here are some examples of JScript literal expressions. 3.9 "Hello!" false null {x:1, y:2} [1,2,3] function(x){return x*x;}
2
// // // // // // //
numeric literal string literal boolean literal literal null value Object literal Array literal function literal
Writing JScript Code
Writing JScript Code
3
More complicated expressions can contain variables, function calls, and other expressions. You can combine expressions to create complex expressions using operators. Examples of operators are: + * /
// // // //
additon subtraction multiplication division
Here are some examples of JScript complex expressions. var var var var
anExpression = 3 * (4 / 5) + 6; aSecondExpression = Math.PI * radius * radius; aThirdExpression = aSecondExpression + "%" + anExpression; aFourthExpression = "(" + aSecondExpression + ") % (" + anExpression + ")";
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
Writing JScript Code
3
4
Writing JScript Code
4
Writing JScript Code
JScript Variables In 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 you use 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 appear in your scripts. Always create a meaningful variable name; that makes it easy for humans to understand what your scripts do.
Declaring Variables The first time a variable appears in your script is its declaration. This first mention of the variable sets it up in memory so you can refer to it later on in your script. Always declare variables before using them. You do this using the var keyword. 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 value undefined. Although it is unsafe to do so, it is legal JScript syntax to omit the var keyword from your declaration statement. When you do, the JScript interpreter gives the variable global scope visibility. When you declare a variable at the procedure level though, you do not want it to be visible at the global scope; in this case, you must use the var keyword in your variable declaration.
Naming Variables A variable name is an identifier. In JScript, identifiers are used to: • name variables, • name functions, • provide labels for loops. JScript is a case-sensitive language. This means a variable name such as myCounter is different than the variable name MYCounter. Variable names can be of any length. The rules for creating legal variable names are as follows: • The first character must be an ASCII letter (either uppercase or lowercase), or an underscore (_) character. Note that a number cannot be used as the first character. • Subsequent characters must be letters, numbers, or underscores. • The variable name must not be a reserved word. Here are some examples of valid variable names: _pagecount Part9 Number_Items
JScript Variables
1
2
JScript Variables
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 it the 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 is an example. var currentCount; var finalCount = 1 * currentCount; // finalCount has the value NaN since currentCount is undefined.
Note that the main difference between null and undefined in JScript is that null behaves like the number 0, while undefined behaves like the special value NaN (Not a Number). A null value and an undefined value will always compare to be equal. You can declare a variable without using the var keyword in the declaration, and assign a value to it. This is an implicit declaration. 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 number and a string for example) would produce an erroneous result. But that is not the case with JScript. JScript is a loosely typed language. This means its variables have no predetermined type (as opposed to strongly typed languages like C++). Instead, JScript variables have a type that corresponds to the type of value they contain. A benefit of this behavior is that it provides you with the flexibility to treat a value as if it were of another type. In JScript, you can perform operations on values of differing types without fear that the JScript interpreter will raise an exception. Instead, the JScript interpreter automatically changes (coerces) one of the data types to that of the other, then performs the operation. For example: Operation Add a number and a string Add a Boolean and a string Add a number and a Boolean Consider the following example. var x = 2000; var y = "Hello"; x = x + y; document.write(x);
2
// // // //
Result The number is coerced into a string. The Boolean is coerced into a string. The Boolean is coerced into a number.
A number. A string. the number is coerced into a string. Outputs 2000Hello.
JScript Variables
JScript Variables
3
To explicitly convert a string to an integer, use the parseInt Method. To explicitly convert a string to a number, use the parseFloat Method. Notice that strings are automatically converted to equivalent numbers for comparison purposes, but are left as strings for addition (concatenation).
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
JScript Variables
3
4
JScript Variables
4
JScript Variables
JScript Data Types In JScript, there are three primary data types, two composite data types, and two special data types. 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) strung together. You use the string data type to represent text in JScript. String literals can be included in your scripts by enclosing them in matching pairs of single or double quotation marks. Double quotation marks can be contained within strings surrounded by single quotation marks, and single quotation marks can be contained within 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 in JScript, you create a string that consists of only one character. A string that contains zero characters ("") is an empty (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 in base 10 (decimal), base 8 (octal), and base 16 (hexadecimal). Most numbers in JScript are written in decimal. You denote octal integers by prefixing them with a leading "0" (zero). They can contain digits 0 through 7 only. A number with a leading "0", containing the digits "8" and/or "9" is interpreted as a decimal number. You denote hexadecimal ("hex") integers by prefixing them with a leading "0x" (zero and x|X). They can contain digits 0 through 9, and letters A through F (either uppercase or lowercase) only. The letters A through F are used to represent, as single digits, 10 through 15 in base 10. That is, 0xF is equivalent to 15, and 0x10 is equivalent to 16. JScript Data Types
1
2
JScript Data Types
Both octal and hexadecimal numbers can be negative, but cannot have a decimal portion, and cannot be written in scientific (exponential) notation.
Floating-point Values Floating-point values can be whole numbers with a decimal portion. Additionally, they can be expressed in scientific notation. That is, an uppercase or lowercase "e" is used to represent "ten to the power of". JScript represents numbers using the eight byte IEEE 754 floating-point standard for numerical representation. This means you can write numbers as large as ±1.7976931348623157x10308, and as small as ±5x10-324. A number that begins with a single "0" and contains a decimal point is interpreted as a decimal floating-point number. Notice that a number that begins with "0x" or "00" and contains a decimal point will generate an error. Here are some examples of JScript numbers. Number .0001, 0.0001, 1e-4, 1.0e-4 3.45e2 42 0378
Description Four equivalent floating-point numbers. A floating-point number. An integer. An integer. Although this looks like an octal number (it begins with a zero), 8 is not a valid octal digit, so the number is treated as a decimal. 0377 An octal integer. Notice that although it only appears to be one less than the number above, its actual value is quite different. 0.0001 A floating point number. Even though this begins with a zero, it is not an octal number because it has a decimal point. 00.0001 This is an error. The two leading zeros mark the number as an octal, but octals are not allowed a decimal component. 0Xff A hexadecimal integer. 0x37CF A hexadecimal integer. 0x3e7 A hexadecimal integer. Notice that the 'e' is not treated as exponentiation. 0x3.45e2 This is an error. Hexadecimal numbers cannot have decimal parts. Additionally, JScript contains numbers with special values. These are:
Decimal Equivalent 0.0001 345 42 378
255
0.0001
N/A (compiler error)
255 14287 999 N/A (compiler error)
• 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, the Boolean 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
JScript Data Types
3
Comparisons you make in your scripts always have a Boolean outcome. Consider the following line of JScript code. y = (x == 2000);
Here, the value of the variable x is tested to see if it is equal to the number 2000. If it is, the result of the comparison is the Boolean value true, which is assigned to the variable y. If x is not equal to 2000, then the result of the comparison is the Boolean value false. Boolean values are especially useful in control structures. Here, you combine a comparison that creates a Boolean value directly with a statement that uses it. Consider the following JScript code sample. if (x == 2000) z = z + 1; else x = x + 1;
The if/else statement in JScript performs one action if a Boolean value is true (in this case, z = z + 1), and an alternate action if the Boolean value is false (x = x + 1). You can use any expression as a comparative expression. Any expression that evaluates to 0, null, undefined, or an empty string is interpreted as false. An expression that evaluates to any other value is interpreted as true. For example, you could use an expression such as: 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) is used. Instead, the code above assigns the value of y + z to the variable x, and then checks if the result of the entire expression (the value of x) is zero. To check if x is equal to y + z, use the following code. 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 a function 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) by assigning it the null value. Notice that in JScript, null is not the same as 0 (as it is in C and C++). Also note that the typeof operator in JScript will report null values as being of type Object, not of type null. This potentially confusing behavior is for backwards compatibility.
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
4
JScript Data Types
Notice that you cannot test to see if a variable exists by comparing it to undefined, although you can check if its type is "undefined". In the following code example, assume that the programmer is trying to test if the variable x has been declared: // This method will not work if (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 work if (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
JScript Operators JScript has a full range of operators, including arithmetic, logical, bitwise, assignment, as well as some miscellaneous operators. Computational Operators Description Unary negation Increment Decrement Multiplication Division Modulus arithmetic Addition Subtraction Logical Operators
Symbol ++ * / % + -
Description Logical NOT Less than Greater than Less than or equal to Greater than or equal to Equality Inequality Logical AND Logical OR Conditional (ternary) Comma Strict Equality Strict Inequality Bitwise Operators
Symbol ! < > = == != && || ?: , === !==
Description Bitwise NOT Bitwise Left Shift Bitwise Right Shift Unsigned Right Shift Bitwise AND Bitwise XOR Bitwise OR Assignment Operators
Symbol ~ > >>> & ^ |
Description Assignment
JScript Operators
Symbol =
1
2
JScript Operators
Compound Assignment Miscellaneous Operators
OP=
Description
Symbol
delete delete typeof typeof void void instanceof instanceof new new in in The difference between == (equality) and === (strict equality) is that the equality operator will coerce values of different types before checking for equality. For example, comparing the string "1" with the number 1 will compare as true. The strict equlity operator, on the other hand, will not coerce values to different types, and so the string "1" will not compare as equal to the number 1. Primitive strings, numbers, and Booleans are compared by value. If they have the same value, they will compare as equal. Objects (including Array, Function, String, Number, Boolean, Error, Date and RegExp objects) compare by reference. Even if two variables of these types have the same value, they will only compare as true if they refer to exactly the same object. For example: // 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
Controlling Program Flow Normally, statements in a JScript script are executed one after the other, in the order in which they are written. This is called sequential execution, and is the default direction of program flow. An alternative to sequential execution transfers the program flow to another part of your script. That is, instead of executing the next statement in the sequence, another statement is executed instead. To make a script useful, this transfer of control must be done in a logical manner. Transfer of program control is based upon a decision, the result of which is a truth statement (returning a Boolean true or false). You create an expression, then test whether its result is true. There are two main kinds of program structures that accomplish this. The first is the selection structure. You use it to specify alternate courses of program flow, creating a junction in your program (like a fork in a road). There are four selection structures available in JScript. • the 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 is to be repeated while some condition remains true. When the conditions of the control statement have been met (usually after some specific number of iterations), control passes to the next statement beyond the repetition structure. There are four repetition structures available in JScript. • 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 this document.
Using Conditional Statements JScript supports if and if...else conditional statements. In if statements a condition is tested, and if the condition meets the test, the relevant JScript code is executed. In the if...else statement, different code is executed if the condition fails the test. The simplest form of an if statement can be written on one line, but multiline 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 example shows the simplest kind of Boolean test. If (and only if) the item between the parentheses evaluates to (or can be coerced to) true, the statement or block of statements after the if is executed. // 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
2
Controlling Program Flow 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 condition is 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 than the others, you can use a feature called 'short circuit evaluation' to speed the execution of your script. When JScript evaluates a logical expression, it only evaluates as many sub-expressions as required to get a result. For example, if you have andAnd' expression such as ((x == 123) && (y == 42)), JScript first checks if x is 123. If it is not, the entire expression cannot be true, even if y is equal to 42. Hence, the test for y is never made, and JScript returns the value false. Similarly, if only one of several conditions must be true (using the || operator), testing stops as soon as any one condition passes the test. This is effective if the conditions to be tested involve the execution of function calls or other complex expressions. With this in mind, when you write Or expressions, place the conditions most likely to be true first. When you write And expressions, place the conditions most likely to be false first. A benefit of designing your script in this manner is that runsecond() will not be executed in the following example if runfirst() returns 0 or false. if ((runfirst() == 0) || (runsecond() == 0)) { // some code }
Using Loops There are several ways to execute a statement or block of statements repeatedly. In general, repetitive execution is called looping or iteration. An iteration is simply a single execution of a loop. It is typically controlled by a test of a variable, where the value of which is changed each time the loop is executed. JScript supports four types of loops: for loops, for...in loops, while loops, do...while loops.
2
Controlling Program Flow
Controlling Program Flow
3
Using for Loops The for statement specifies a counter variable, a test condition, and an action that updates the counter. Before each 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 line of code immediately following the loop. After the loop is executed, the counter variable is updated before the next iteration begins. If the condition for looping is never met, the loop is never executed. If the test condition is always met, an infinite loop results. While the former may be desirable in certain cases, the latter rarely is, so be cautious when writing your loop conditions. /* The update expression ("icount++" in the following examples) is executed at the end of the loop, after the block of statements that forms the body of the loop is executed, and before the condition is tested. */ var 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 n newSum += 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 all the elements of an array. The loop counter in a for...in loop is a string, not a number. It contains the name of current 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, which is not a part of JScript. // Create an object with some properties var myObject = new Object(); myObject.name = "James"; myObject.age = "22"; myObject.phone = "555 1234"; // Enumerate (loop through)_all the properties in the object for (prop in myObject) { // This displays "The property 'name' is James", etc. window.alert("The property '" + prop + "' is " + myObject[prop]); }
Controlling Program Flow
3
4
Controlling Program Flow
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 loop iterates 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 and JScript'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 variable or update expression. If you want to control repetitive execution of a statement or block of statements, but need a more complex rule than simply "run this code n times", use a while loop. The following example uses the 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 more vulnerable to infinite looping than the other types of loops. Moreover, because it is not necessarily easy to discover where or when the loop condition is updated, it is easy to write a while loop in which the condition never gets updated. For this reason, you should be careful when you design while loops. As noted above, there is also a do...while loop in JScript that is similar to the while loop, except that it is guaranteed to always execute at least once, since the condition is tested at the end of the loop, rather than at the start. For example, the loop above can be re-written as: var x = 0; do { x = window.prompt("What is my favourite number?", x); } while ((x != 42) && (x != null)); if (x == null) window.alert("You gave up!"); else window.alert("Yep - it's the Ultimate Answer!");
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 immediately to the next iteration, skipping the rest of the code block, while updating the counter variable if the loop is a for or for...in loop. The following example builds on the previous example to use the break and continue statements to control the loop. var x = 0; do {
4
Controlling Program Flow
Controlling Program Flow
5
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
6
Controlling Program Flow
6
Controlling Program Flow
JScript Objects JScript objects are collections of properties and methods. A method is a function that is a member of an object. 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 by the 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 to them, and indeed Arrays are merely a special kind of Object. The difference between Arrays and Objects is that arrays have a "magic" length property, whilst objects do not. This means that if you assign a value to an element of an array that is greater than every other element for example, myArray[100] = "hello" then the length property will automatically be updated to be 101 (the new length). Similarly, if you modify the length property of an array, it will delete any elements that are no longer part of the array. All objects in JScript support "expando" properties, or properties that can be added and removed dynamically at run time. These properties can have any name, including numbers. If the name of the property is a simple identifier, 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, you can use an arbitrary expression inside square brackets to index the property. The names of all expando properties in JScript are converted to strings before being added to the object. 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 brackets myObj[100] = "100";
Traditionally, array elements are given numeric indices, starting at zero. It is these elements that interact with the length property. Nevertheless, because all arrays are also objects, they support expando properties as well. Note, though, that expando properties do not interact with the length property in any way. For example: // An array with three elements var myArray = new Array(3); // Add some data myArray[0] = "Hello"; myArray[1] = 42; myArray[2] = new Date(2000, 1, 1); // This will display 3, the length of the array window.alert(myArray.length); // Add some expando properties myArray.expando = "JScript!";
JScript Objects
1
2
JScript Objects
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 inside array elements including other arrays. So you can get the behavior of multi-dimensional arrays by storing arrays within the elements of another array. For example, the following code builds a multiplication table for the numbers up to 5: // Change this number for a bigger table var iMaxNum = 5; // Loop counters var 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 document.write(VBArrayTest(CreateVBArray()));
dimensions Method
1
2
dimensions Method
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
escape Method Encodes 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. All spaces, punctuation, accented characters, and any other non-ASCII characters are replaced with %xx encoding, where xx is equivalent to the hexadecimal number representing the character. For example, a space is returned as "%20." Characters with a value greater than 255 are stored using the %uxxxx format. Note The escape method should not be used to encode Uniform Resource Identifiers (URI). Use encodeURI and encodeURIComponent methods instead. Requirements Version 1 See Also 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
2
escape Method
2
escape Method
eval Method Evaluates JScript code and executes it. eval(codeString)
The required codeString argument is a string value that contains valid JScript code. This string is parsed by the JScript parser and executed. Remarks The eval function allows dynamic execution of JScript source code. For example, the following code creates a new variable mydate that contains a Date object: 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
2
eval Method
2
eval Method
exec Method Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. rgExp.exec(str)
Arguments rgExp Required. An instance of a Regular Expression object containing the regular expression pattern and applicable flags. str Required. The String object or string literal on which to perform the search. Remarks If the exec method does not find a match, it returns null. If it finds a match, exec returns an array, and the properties of the global RegExp object are updated to reflect the results of the match. Element zero of the array contains the entire match, while elements 1 n contain any submatches that have occurred within the match. This behavior is identical to the behavior of the match method without the global flag (g) set. If the global flag is set for a regular expression, exec searches the string beginning at the position indicated by the value of lastIndex. If the global flag is not set, exec ignores the value of lastIndex and searches from the beginning of the string. The array returned by the exec method has three properties, input, index and lastIndex. The input property contains the entire searched string. The index property contains the position of the matched substring within the complete searched string. The lastIndex property contains the position following the last character in the match. Example 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
2
exec Method
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
exp Method Returns 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 the supplied 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
2
exp Method
2
exp Method
fixed Method Places HTML 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: This is a string object
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
2
fixed Method
2
fixed Method
floor Method Returns 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
2
floor Method
2
floor Method
fontcolor Method Places an HTML tag with the COLOR attribute around the text in a String object. strVariable.fontcolor(colorVal)
Arguments strVariable Required. Any String object or literal. colorVal Required. String value containing a color value. This can either be the hexadecimal value for a color, or the predefined name for a color. Remarks 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: This is a string
Valid predefined color names depend on your JScript host (browser, server, and so forth). They may also vary from version to version of your host. Check your host documentation for more information. No checking is done to see if the tag has already been applied to the string. Requirements Version 1 See Also 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
2
fontcolor Method
2
fontcolor Method
fontsize Method Places an HTML tag with the SIZE attribute around the text in a String object. strVariable.fontsize(intSize)
Arguments strVariable Required. Any String object or literal. intSize Required. Integer value that specifies the size of the text. Remarks 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: This is a string
Valid integer values depend on your Microsoft JScript host. See your host documentation for more information. No checking is done to see if the tag has already been applied to the string. Requirements Version 1 See Also 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
2
fontsize Method
2
fontsize Method
getDate Method Returns 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
2
getDate Method
2
getDate Method
getDay Method Returns 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 week and corresponds to a day of the week as follows: Value
Day of the Week
0 Sunday 1 Monday 2 Tuesday 3 Wednesday 4 Thursday 5 Friday 6 Saturday The 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
2
getDay Method
2
getDay Method
getHours Method Returns 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. A zero occurs in two situations: the time is before 1:00:00 am, or the time was not stored in the Date object when the object was created. The only way to determine which situation you have is to also check the minutes and seconds for zero values. If they are all zeroes, it is nearly certain that the time was not stored in the Date object. 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
2
getHours Method
2
getHours Method
getMinutes Method Returns 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 Date object. A zero is returned in two situations: when the time is less than one minute after the hour, or when the time was not stored in the Date object when the object was created. The only way to determine which situation you have is to also check the hours and seconds for zero values. If they are all zeroes, it is nearly certain that the time was not stored in the Date object. Example 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
2
getMinutes Method
2
getMinutes Method
getMonth Method Returns 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. The integer returned is not the traditional number used to indicate the month. It is one less. If "Jan 5, 1996 08:47:00" is stored in a Date object, getMonth returns 0. Example 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
2
getMonth Method
2
getMonth Method
getSeconds Method Returns 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 indicated Date object. A zero is returned in two situations. One occurs when the time is less than one second into the current minute. The other occurs when the time was not stored in the Date object when the object was created. The only way to determine which situation you have is to also check the hours and minutes for zero values. If they are all zeroes, it is nearly certain that the time was not stored in the Date object. Example 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
2
getSeconds Method
2
getSeconds Method
getTime Method Returns 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 years from either side of midnight, January 1, 1970. Negative numbers indicate dates prior to 1970. When doing multiple date and time calculations, it is frequently useful to define variables equal to the number of milliseconds in a day, hour, or minute. For example: var MinMilli = 1000 * 60 var HrMilli = MinMilli * 60 var 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
2
getTime Method
2
getTime Method
getTimezoneOffset Method Returns the difference in minutes between the time on the host computer and Universal Coordinated Time (UTC). dateObj.getTimezoneOffset()
The required dateObj reference is a Date object. Remarks The getTimezoneOffset method returns an integer value representing the number of minutes between the time on the current machine and UTC. These values are appropriate to the computer the script is executed on. If it is called from a server script, the return value is appropriate to the server. If it is called from a client script, the return value is appropriate to the client. This number will be positive if you are behind UTC (e.g., Pacific Daylight Time), and negative if you are ahead of UTC (e.g., Japan). For example, suppose a server in New York City is contacted by a client in Los Angeles on December 1. getTimezoneOffset returns 480 if executed on the client, or 300 if executed on the server. Example 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
2
getTimezoneOffset Method
2
getTimezoneOffset Method
getVarDate Method Returns 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 that accept and return date values in VT_DATE format, such as Visual Basic and VBScript. The actual format is dependent on regional settings and should not be replied upon within JScript. Requirements Version 3 See Also 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
2
getVarDate Method
2
getVarDate Method
getYear Method Returns 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 method instead. For the years 1900 though 1999, the year is a 2-digit integer value returned as the difference between the stored year and 1900. For dates outside that period, the 4-digit year is returned. For example, 1996 is returned as 96, but 1825 and 2025 are returned as-is. Note For JScript version 1.0, getYear returns a value that is the result of the subtraction of 1900 from the year value in the provided Date object, regardless of the value of the year. For example, the year 1899 is returned as -1 and the year 2000 is returned as 100. Example 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
2
getYear Method
2
getYear Method
indexOf Method Returns the character position where the first occurrence of a substring occurs within a String object. strObj.indexOf(subString[, startIndex])
Arguments strObj Required. A String object or literal. subString Required. Substring to search for within the String object. startIndex Optional. Integer value specifying the index to begin searching within the String object. If omitted, searching starts at the beginning of the string. Remarks The indexOf method returns an integer value indicating the beginning of the substring within the String object. If the substring is not found, a -1 is returned. If startindex is negative, startindex is treated as zero. If it is larger than the greatest character position index, it is treated as the largest possible index. Searching is performed from left to right. Otherwise, this method is identical to lastIndexOf. Example 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
2
indexOf Method
2
indexOf Method
italics Method Places HTML 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: This is a string
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
2
italics Method
2
italics Method
item Method Returns 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 returns undefined. Example In following code, the item method is used to return a member of the Drives collection. function ShowDriveList(){ var fso, s, n, e, x; fso = new ActiveXObject("Scripting.FileSystemObject"); e = new Enumerator(fso.Drives); s = ""; for (; !e.atEnd(); e.moveNext()) { x = e.item(); s = s + x.DriveLetter; s += " - "; if (x.DriveType == 3) n = x.ShareName; else if (x.IsReady) n = x.VolumeName; else n = "[Drive not ready]"; s += n + ""; } 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
2
item Method
2
item Method
join Method Returns a string value consisting of all the elements of an array concatenated together and separated by the specified separator character. arrayObj.join(separator)
Arguments arrayObj Required. An Array object. separator Required. A String object used to separate one element of an array from the next in the resulting String object. If omitted, the array elements are separated with a comma. Remarks 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
2
join Method
2
join Method
lastIndexOf Method Returns the last occurrence of a substring within a String object. strObj.lastIndexOf(substring[, startindex])
Arguments strObj Required. A String object or literal. substring Required. The substring to search for within the String object. startindex Optional. Integer value specifying the index to begin searching within the String object. If omitted, searching begins at the end of the string. Remarks The lastIndexOf method returns an integer value indicating the beginning of the substring within the String object. If the substring is not found, a -1 is returned. If startindex is negative, startindex is treated as zero. If it is larger than the greatest character position index, it is treated as the largest possible index. 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
2
lastIndexOf Method
2
lastIndexOf Method
lbound Method Returns the lowest index value used in the specified dimension of a VBArray. safeArray.lbound(dimension)
Arguments safeArray Required. A VBArray object. dimension Optional. The dimension of the VBArray for which the lower bound index is wanted. If omitted, lbound behaves as if a 1 was passed. Remarks If the VBArray is empty, the lbound method returns undefined. If dimension is greater than the number of dimensions in the VBArray, or is negative, the method generates a "Subscript out of range" error. Example The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is JScript code that determines the number of dimensions in the safe array and the lower bound of each dimension. Since the safe array is created in VBScript rather than Visual Basic, the lower bound will always be zero. Both of these parts go into the section of an HTML page. The third part is the JScript code that goes in the section to run the other two parts.
lbound Method
1
2
lbound Method
document.write(VBArrayTest(CreateVBArray()));
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
link Method Places an HTML anchor with an HREF attribute around the text in a String object. strVariable.link(linkstring) "String Literal".link(linkstring)
The linkstring argument is the text that you want to place in the HREF attribute of the HTML anchor. Remarks Call the link method to create a hyperlink out of a String object. The following is an example of how the method accomplishes this: var strVariable = "This is a hyperlink"; strVariable = strVariable.link("http://www.microsoft.com");
The value of strVariable after the last statement is: This is a hyperlink
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
2
link Method
2
link Method
log Method Returns the natural logarithm of a number. Math.log(number)
The required number argument is a numeric expression for which the natural logarithm is sought. Return Value 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
2
log Method
2
log Method
match Method Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. stringObj.match(rgExp)
Arguments stringObj Required. The String object or string literal on which to perform the search. rgExp Required. An instance of a Regular Expression object containing the regular expression pattern and applicable flags. Can also be a variable name or string literal containing the regular expression pattern and flags. Remarks If the match method does not find a match, it returns null. If it finds a match, match returns an array, and the properties of the global RegExp object are updated to reflect the results of the match. The array returned by the match method has three properties, input, index and lastIndex. The input property contains the entire searched string. The index property contains the position of the matched substring within the complete searched string. The lastIndex property contains the position following the last character in the last match. If the global flag (g) is not set, Element zero of the array contains the entire match, while elements 1 n contain any submatches that have occurred within the match. This behavior is identical to the behavior of the exec method without the global flag set. If the global flag is set, elements 0 - n contain all matches that occurred. Example 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
2
match Method
r = "The rain in Spain".replace(re, "Canada");
Requirements Version 3 See Also exec Method | RegExp Object | replace Method | search Method | String Object Methods | test Method Applies To: String Object
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
2
match Method
max Method Returns 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
2
max Method
2
max Method
min Method Returns 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
2
min Method
2
min Method
parse Method Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. Date.parse(dateVal)
The required dateVal argument is either a string containing a date in a format such as "Jan 5, 1996 08:47:00" or a VT_DATE value retrieved from an ActiveX® object or other object. Remarks The parse method returns an integer value representing the number of milliseconds between midnight, January 1, 1970 and the date supplied in dateVal. The parse method is a static method of the Date object. Because it is a static method, it is invoked as shown in the following example, rather than invoked as a method of a created Date object. 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, for example "7/20/96". • Long dates of the form "July 10 1995" can be given with the year, month, and day in any order, and the year in 2-digit or 4-digit form. If you use the 2-digit form, the year must be greater than or equal to 70. • Any text inside parentheses is treated as a comment. These parentheses may be nested. • Both commas and spaces are treated as delimiters. Multiple delimiters are permitted. • Month and day names must have two or more characters. Two character names that are not unique are resolved as the last match. For example, "Ju" is resolved as July, not June. • The stated day of the week is ignored if it is incorrect given the remainder of the supplied date. For example, "Tuesday November 9 1996" is accepted and parsed even though that date actually falls on a Friday. The resulting Date object contains "Friday November 9 1996". • JScript handles all standard time zones, as well as Universal Coordinated Time (UTC) and Greenwich Mean Time (GMT). • Hours, minutes, and seconds are separated by colons, although all need not be specified. "10:", "10:11", and "10:11:12" are all valid. • If the 24-hour clock is used, it is an error to specify "PM" for times later than 12 noon. For example, "23:15 PM" is an error. • A string containing an invalid date is an error. For example, a string containing two years or two months is an error. Example The following example illustrates the use of the parse method. Provide the function with a date and the function will return the difference between the date provided and 1/1/1970: function GetTimeTest(testdate){ var s, t; //Declare variables. var MinMilli = 1000 * 60; //Initialize variables. var HrMilli = MinMilli * 60; var DyMilli = HrMilli * 24; t = Date.parse(testdate); //Parse testdate. s = "There are " //Create return string.
parse Method
1
2
parse Method s += Math.round(Math.abs(t / DyMilli)) + " days " s += "between " + testdate + " and 1/1/70"; return(s); //Return results.
}
Requirements Version 1 See Also Date Object Methods Applies To: Date Object
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
2
parse Method
parseFloat Method Returns 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 of numString can be successfully parsed into a floating-point number, NaN (not a number) is returned. parseFloat("abc") parseFloat("1.2abc")
// Returns NaN. // 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
2
parseFloat Method
2
parseFloat Method
parseInt Method Returns an integer converted from a string. parseInt(numString, [radix])
Arguments numString Required. A string to convert into a number. radix Optional. A value between 2 and 36 indicating the base of the number contained in numString. If not supplied, strings with a prefix of '0x' are considered hexadecimal and strings with a prefix of '0' are considered octal. All other strings are considered decimal. Remarks The parseInt method returns an integer value equal to the number contained in numString. If no prefix of numString can be successfully parsed into an integer, NaN (not a number) is returned. parseInt("abc") parseInt("12abc")
// Returns NaN. // 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
2
parseInt Method
2
parseInt Method
pow Method Returns the value of a base expression taken to a specified power. Math.pow(base, exponent)
Arguments base Required. The base value of the expression. exponent Required. The exponent value of the expression. Example 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
2
pow Method
2
pow Method
random Method Returns a pseudorandom number between 0 and 1. Math.random( )
Remarks The pseudorandom number generated is from 0 (inclusive) to 1 (exclusive), that is, the returned number can be zero, but it will always be less than one. The random number generator is seeded automatically when JScript is first loaded. Requirements Version 1 See Also Math Object Methods Applies To: Math Object
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
random Method
1
2
random Method
2
random Method
replace Method Returns a copy of a string with text replaced using a regular expression or search string. stringObj.replace(rgExp, replaceText)
Arguments stringObj Required. The String object or string literal on which to perform the replacement. This string is not modified by the replace method. rgExp Required. An instance of a Regular Expression object containing the regular expression pattern and applicable flags. Can also be a String object or literal. If rgExp is not an instance of a Regular Expression object, it is converted to a string, and an exact search is made for the results; no attempt is made to convert the string into a regular expression. replaceText Required. A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. In JScript 5.5 or later, the replaceText argument can also be a function that returns the replacement text. Remarks The result of the replace method is a copy of stringObj after the specified replacements have been made. Any of the following match variables can be used to identify the most recent match and the string from which it came. The match variables can be used in text replacement where the replacement string has to be determined dynamically. Characters
Meaning
$ (JScript 5.5 or later) Specifies that portion of stringObj that the entire pattern matched. (JScript 5.5 or later) Specifies that portion of stringObj that precedes the match described by $&. (JScript 5.5 or later) $' Specifies that portion of stringObj that follows the match described by $&. (JScript 5.5 or later) $n The nth captured submatch, where n is a single decimal digit from 1 through 9. (JScript 5.5 or later) $nn The nnth captured submatch, where nn is a two-digit decimal number from 01 through 99. (JScript 5.5 or later) If replaceText is a function, for each matched substring the function is called with the following m + 3 arguments where m is the number of left capturing parentheses in the rgExp. The first argument is the substring that matched. The next m arguments are all of the captures that resulted from the search. Argument m + 2 is the offset within stringObj where the match occurred, and argument m + 3 is stringObj. The result is the string value that results from replacing each matched substring with the corresponding return value of the function call. $$ $& $`
The replace method updates the properties of the global RegExp object.
replace Method
1
2
replace Method
Example The following example illustrates the use of the replace method to replace the first instance of the word "The" with the word "A." function ReplaceDemo(){ var r, re; //Declare variables. var ss = "The man hit the ball with the bat.\n"; ss += "while the fielder caught the ball with the glove."; re = /The/g; //Create regular expression pattern. r = ss.replace(re, "A"); //Replace "A" with "The". return(r); //Return string with replacement made. }
In addition, the replace method can also replace subexpressions in the pattern. The following example swaps each pair of words in the string. function ReplaceDemo(){ var r, re; //Declare variables. var ss = "The rain in Spain falls mainly in the plain."; re = /(\S+)(\s+)(\S+)/g; //Create regular expression pattern. r = ss.replace(re, "$3$2$1"); //Swap each pair of words. return(r); //Return resulting string. }
The following example, which works in JScript 5.5 and later, performs a Fahrenheit to Celsius conversion, illustrates using a function as replaceText. To see how this function works, pass in a string containing a number followed immediately by an "F" (e.g., "Water boils at 212"). function f2c(s) { var test = /(\d+(\.\d*)?)F\b/g; //Initialize pattern. return(s.replace (test, function($0,$1,$2) { return((($1-32) * 5/9) + "C"); } ) ); } document.write(f2c("Water freezes at 32F and boils at 212F."));
Requirements Version 1 See Also exec Method | match Method | RegExp Object | search Method | String Object Methods | test Method Applies To: String Object
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
2
replace Method
reverse Method Returns 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 object during execution. If the array is not contiguous, the reverse method creates elements in the array that fill the gaps in the array. Each of these created elements has the value undefined. Example The following example illustrates the use of the reverse method. function ReverseDemo(){ var a, l; a = new Array(0,1,2,3,4); l = a.reverse(); return(l); }
//Declare variables. //Create an array and populate it. //Reverse the contents of the array. //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
2
reverse Method
2
reverse Method
round Method Returns a supplied numeric expression rounded to the nearest integer. Math.round(number)
The required number argument is the value to be rounded to the nearest integer. Remarks If the decimal portion of number is 0.5 or greater, the return value is equal to the smallest integer greater than number. Otherwise, round returns the largest integer less than or equal to number. Requirements Version 1 See Also Math Object Methods Applies To: Math Object
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
round Method
1
2
round Method
2
round Method
search Method Returns the position of the first substring match in a regular expression search. stringObj.search(rgExp)
Arguments stringObj Required. The String object or string literal on which to perform the search. rgExp Required. An instance of a Regular Expression object containing the regular expression pattern and applicable flags. Remarks The search method indicates if a match is present or not. If a match is found, the search method returns an integer value that indicates the offset from the beginning of the string where the match occurred. If no match is found, it returns -1. Example 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
2
search Method
2
search Method
setDate Method Sets the numeric date of the Date object using local time. dateObj.setDate(numDate)
Arguments dateObj Required. Any Date object. numDate Required. A numeric value equal to the numeric date. Remarks To set the date value using Universal Coordinated Time (UTC), use the setUTCDate method. If the value of numDate is greater than the number of days in the month stored in the Date object or is a negative number, the date is set to a date equal to numDate minus the number of days in the stored month. For example, if the stored date is January 5, 1996, and setDate(32) is called, the date changes to February 1, 1996. Negative numbers have a similar behavior. Example 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
2
setDate Method
2
setDate Method
setHours Method Sets the hour value in the Date object using local time. dateObj.setHours(numHours[, numMin[, numSec[, numMilli]]])
Arguments dateObj Required. Any Date object. numHours Required. A numeric value equal to the hours value. numMin Optional. A numeric value equal to the minutes value. Must be supplied if either of the following arguments is used. numSec Optional. A numeric value equal to the seconds value. Must be supplied if the following argument is used. numMilli Optional. A numeric value equal to the milliseconds value. Remarks All set methods taking optional arguments use the value returned from corresponding get methods, if you do not specify an optional argument. For example, if the numMinutes argument is optional, but not specified, JScript uses the value returned from the getMinutes method. To set the hours value using Universal Coordinated Time (UTC), use the setUTCHours method. If the value of an argument is greater than its range or is a negative number, other stored values are modified accordingly. For example, if the stored date is "Jan 5, 1996 00:00:00", and setHours(30) is called, the date is changed to "Jan 6, 1996 06:00:00." Negative numbers have a similar behavior. Example 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
2
setHours Method
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
2
setHours Method
setMonth Method Sets the month value in the Date object using local time. dateObj.setMonth(numMonth[, dateVal])
Arguments dateObj Required. Any Date object. numMonth Required. A numeric value equal to the month. dateVal Optional. A numeric value representing the date. If not supplied, the value from a call to the getDate method is used. Remarks To set the month value using Universal Coordinated Time (UTC), use the setUTCMonth method. If the value of numMonth is greater than 11 (January is month 0) or is a negative number, the stored year is modified accordingly. For example, if the stored date is "Jan 5, 1996" and setMonth(14) is called, the date is changed to "Mar 5, 1997." Example 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
2
setMonth Method
2
setMonth Method
setSeconds Method Sets the seconds value in the Date object using local time. dateObj.setSeconds(numSeconds[, numMilli])
Arguments dateObj Required. Any Date object. numSeconds Required. A numeric value equal to the seconds value. numMilli Optional. A numeric value equal to the milliseconds value. Remarks All set methods taking optional arguments use the value returned from corresponding get methods, if you do not specify an optional argument. For example, if the numMilli argument is optional, but not specified, JScript uses the value returned from the getMilliseconds method. To set the seconds value using Universal Coordinated Time (UTC), use the setUTCSeconds method. If the value of an argument is greater than its range or is a negative number, other stored values are modified accordingly. For example, if the stored date is "Jan 5, 1996 00:00:00" and setSeconds(150) is called, the date is changed to "Jan 5, 1996 00:02:30." Example 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
2
setSeconds Method
Build: Topic Version 5.6.9309.1546 JScript
2
setSeconds Method
setTime Method Sets the date and time value in the Date object. dateObj.setTime(milliseconds)
Arguments dateObj Required. Any Date object. milliseconds Required. An integer value representing the number of elapsed seconds since midnight, January 1, 1970 GMT. Remarks If milliseconds is negative, it indicates a date before 1970. The range of available dates is approximately 285,616 years from either side of 1970. Setting the date and time with the setTime method is independent of the time zone. Example 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
2
setTime Method
2
setTime Method
setYear Method Sets the year value in the Date object. dateObj.setYear(numYear)
Arguments dateObj Required. Any Date object. numYear Required. A numeric value equal to the year minus 1900. Remarks This method is obsolete, and is maintained for backwards compatibility only. Use the setFullYear method instead. To set the year of a Date object to 1997, call setYear(97). To set the year to 2010, call setYear(2010). Finally, to set the year to a year in the range 0-99, use the setFullYear method. Note For JScript version 1.0, setYear uses a value that is the result of the addition of 1900 to the year value provided by numYear, regardless of the value of the year. For example, to set the year to 1899 numYear is -1 and to set the year 2000 numYear is 100. Requirements Version 1 See Also Date Object Methods | getFullYear Method | getUTCFullYear Method | getYear Method | setFullYear Method | setUTCFullYear Method Applies To: Date Object
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
setYear Method
1
2
setYear Method
2
setYear Method
sin Method Returns the sine of a number. Math.sin(number)
The number argument is a numeric expression for which the sine is needed. Remarks 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
2
sin Method
2
sin Method
slice Method (Array) Returns a section of an array. arrayObj.slice(start, [end])
Arguments arrayObj Required. An Array object. start Required. The index to the beginning of the specified portion of arrayObj. end Optional. The index to the end of the specified portion of arrayObj. Remarks The slice method returns an Array object containing the specified portion of arrayObj. The slice method copies up to, but not including, the element indicated by end. If start is negative, it is treated as length + start where length is the length of the array. If end is negative, it is treated as length + end where length is the length of the array. If end is omitted, extraction continues to the end of arrayObj. If end occurs before start, no elements are copied to the new array. Example In the following example, all but the last element of myArray is copied into newArray: 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
2
slice Method (Array)
2
slice Method (Array)
slice Method (String) Returns a section of a string. stringObj.slice(start, [end])
Arguments stringObj Required. A String object or literal. start Required. The index to the beginning of the specified portion of stringObj. end Optional. The index to the end of the specified portion of stringObj. Remarks The slice method returns a String object containing the specified portion of stringObj. The slice method copies up to, but not including, the element indicated by end. If start is negative, it is treated as length + start where length is the length of the string. If end is negative, it is treated as length + end where length is the length of the string. If end is omitted, extraction continues to the end of stringObj. If end occurs before start, no characters are copied to the new string. Example In the following example, the two uses of the slice method return the same result. In the second example, negative one (-1) points to the last character in str1 as the ending point. str1.slice(0) str2.slice(0,-1)
Requirements Version 3 See Also 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
2
slice Method (String)
2
slice Method (String)
small Method Places HTML 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: This is a string
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
2
small Method
2
small Method
sort Method Returns an Array object with the elements sorted. arrayobj.sort(sortFunction)
Arguments arrayObj Required. Any Array object. sortFunction Optional. The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. Remarks The sort method sorts the Array object in place; no new Array object is created during execution. If you supply a function in the sortFunction argument, it must return one of the following values: • A negative value if the first argument passed is less than the second argument. • Zero if the two arguments are equivalent. • A positive value if the first argument is greater than the second argument. Example 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
2
sort Method
2
sort Method
split Method Returns the array of strings that results when a string is separated into substrings. stringObj.split([separator[, limit]])
Arguments stringObj Required. The String object or literal to be split. This object is not modified by the split method. separator Optional. A string or an instance of a Regular Expression object identifying one or more characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. limit Optional. A value used to limit the number of elements returned in the array. Remarks The result of the split method is an array of strings split at each point where separator occurs in stringObj. The separator is not returned as part of any array element. Example 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 Object Methods Applies To: String Object
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
split Method
1
2
split Method
2
split Method
sqrt Method Returns 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
2
sqrt Method
2
sqrt Method
strike Method Places HTML 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: This is a string object
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
2
strike Method
2
strike Method
sub Method Places HTML 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: This is a string object
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
2
sub Method
2
sub Method
substr Method Returns a substring beginning at a specified location and having a specified length. stringvar.substr(start [, length ])
Arguments stringvar Required. A string literal or String object from which the substring is extracted. start Required. The starting position of the desired substring. The index of the first character in the string is zero. length Optional. The number of characters to include in the returned substring. Remarks If length is zero or negative, an empty string is returned. If not specified, the substring continues to the end of stringvar. Example 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
2
substr Method
2
substr Method
substring Method Returns the substring at the specified location within a String object. strVariable.substring(start, end) "String Literal".substring(start, end)
Arguments start The zero-based index integer indicating the beginning of the substring. end The zero-based index integer indicating the end of the substring. Remarks The substring method returns a string containing the substring from start up to, but not including, end. The substring method uses the lower value of start and end as the beginning point of the substring. For example, strvar.substring(0, 3) and strvar.substring(3, 0) return the same substring. 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. For example, 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
2
substring Method
2
substring Method
sup Method Places HTML 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: This is a string object
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
2
sup Method
2
sup Method
tan Method Returns the tangent of a number. Math.tan(number)
The required number argument is a numeric expression for which the tangent is sought. Remarks 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
2
tan Method
2
tan Method
test Method Returns a Boolean value that indicates whether or not a pattern exists in a searched string. rgExp.test(str)
Arguments rgExp Required. An instance of a Regular Expression object containing the regular expression pattern and applicable flags. str Required. The string on which to perform the search. Remarks The test method checks to see if a pattern exists within a string and returns true if so, and false otherwise. The properties of the global RegExp object are not modified by the test method. Example The following example illustrates the use of the test method. To use this example, pass the function a regular expression pattern and a string. The function will test for the occurrence of the regular expression pattern in the string and return a string indicating the results of that search: 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 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
test Method
1
2
test Method
2
test Method
toGMTString Method Returns a date converted to a string using Greenwich Mean Time(GMT). dateObj.toGMTString()
The required dateObj reference is any Date object. Remarks The toGMTString method is obsolete, and is provided for backwards compatibility only. It is recommended that you use the toUTCString method instead. The toGMTString method returns a String object that contains the date formatted using GMT convention. The format of the return value is as follows: "05 Jan 1996 00:00:00 GMT." Requirements Version 1 See Also 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
2
toGMTString Method
2
toGMTString Method
toLocaleString Method Returns 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 long default format. • For dates between 1601 and 1999 A.D., the date is formatted according to the user's Control Panel Regional Settings. • For dates outside this range, the default format of the toString method is used. For example, in the United States, toLocaleString returns "01/05/96 00:00:00" for January 5. In Europe, it returns "05/01/96 00:00:00" for the same date, as European convention puts the day before the month. Note toLocaleString should only be used to display results to a user; it should never be used as the basis for computation within a script as the returned result is machine-specific. Example The following example illustrates the use of the toLocaleString method. function toLocaleStrDemo(){ var d, s; d = new Date(); s = "Current setting is "; s += d.toLocaleString(); return(s); }
//Declare variables. //Create Date object. //Convert to current locale. //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
2
toLocaleString Method
2
toLocaleString Method
toLowerCase Method Returns a string where all alphabetic characters have been converted to lowercase. strVariable.toLowerCase( ) "String Literal".toLowerCase( )
Remarks 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
2
toLowerCase Method
2
toLowerCase Method
toUpperCase Method Returns a string where all alphabetic characters have been converted to uppercase. strVariable.toUpperCase( ) "String Literal".toUpperCase( )
Remarks 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
2
toUpperCase Method
2
toUpperCase Method
ubound Method Returns the highest index value used in the specified dimension of the VBArray. safeArray.ubound(dimension)
Arguments safeArray Required. A VBArray object. dimension Optional. The dimension of the VBArray for which the higher bound index is wanted. If omitted, ubound behaves as if a 1 was passed. Remarks If the VBArray is empty, the ubound method returns undefined. If dim is greater than the number of dimensions in the VBArray, or is negative, the method generates a "Subscript out of range" error. Example The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is JScript code that determines the number of dimensions in the safe array and the upper bound of each dimension. Both of these parts go into the section of an HTML page. The third part is the JScript code that goes in the section to run the other two parts.
ubound Method
1
2
ubound Method
document.write(VBArrayTest(CreateVBArray()));
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
unescape Method Decodes 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 encoded with the %xx hexadecimal form are replaced by their ASCII character set equivalents. Characters encoded in %uxxxx format (Unicode characters) are replaced with the Unicode character with hexadecimal encoding xxxx. Note The unescape method should not be used to decode Uniform Resource Identifiers (URI). Use decodeURI and decodeURIComponent methods instead. Requirements Version 1 See Also 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
2
unescape Method
2
unescape Method
Array Object Provides support for creation of arrays of any data type. arrayObj = new Array() arrayObj = new Array([size]) arrayObj = new Array([element0[, element1[, ...[, elementN]]]])
Arguments arrayObj Required. The variable name to which the Array object is assigned. size Optional. The size of the array. As arrays are zero-based, created elements will have indexes from zero to size -1. element0,...,elementN Optional. The elements to place in the array. This creates an array with n + 1 elements, and a length of n + 1. Using this syntax, you must supply more than one element. Remarks After an array is created, the individual elements of the array can be accessed using [ ] notation, for example: 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 fifth element of the array. That element contains the value 4. If only one argument is passed to the Array constructor, and the argument is a number, it must be an unsigned 32-bit integer (< approximately four billion). That value then becomes the size of the array. If the value is a number, but is less than zero or is not an integer, a run-time error occurs. If a single value is passed to the Array constructor, and it is not a number, the length property is set to 1, and the value of the only element becomes the single, passed-in argument. Notice that JScript arrays are sparse arrays, that is, although you can allocate an array with many elements, only the elements that actually contain data exist. This reduces the amount of memory used by the array. Properties constructor Property | length Property | prototype Property Methods concat Method | join Method | pop Method | push Method | reverse Method | shift Method | slice Method | sort Method | splice Method | toLocaleString Method | toString Method | unshift Method | valueOf Method
Array Object
1
2
Array Object
Requirements Version 2 See Also new Operator
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
2
Array Object
arguments Object An object representing the arguments to the currently executing function, and the functions that called it. [function.]arguments[n]
Arguments function Optional. The name of the currently executing Function object. n Required. The zero-based index to argument values passed to the Function object. Remarks You cannot explicitly create an arguments object. The arguments object only becomes available when a function begins execution. The arguments object of the function is not an array, but the individual arguments are accessed the same way array elements are accessed. The index n is actually a reference to one of the 0
n properties of the arguments object. Example 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
2
arguments Object
JScript
2
arguments Object
Date Object Enables 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 dateObj Required. The variable name to which the Date object is assigned. dateVal Required. If a numeric value, dateVal represents the number of milliseconds in Universal Coordinated Time between the specified date and midnight January 1, 1970. If a string, dateVal is parsed according to the rules in the parse method. The dateVal argument can also be a VT_DATE value as returned from some ActiveX® objects. year Required. The full year, for example, 1976 (and not 76). month Required. The month as an integer between 0 and 11 (January to December). date Required. The date as an integer between 1 and 31. hours Optional. Must be supplied if minutes is supplied. An integer from 0 to 23 (midnight to 11pm) that specifies the hour. minutes Optional. Must be supplied if seconds is supplied. An integer from 0 to 59 that specifies the minutes. seconds Optional. Must be supplied if milliseconds is supplied. An integer from 0 to 59 that specifies the seconds. ms Optional. An integer from 0 to 999 that specifies the milliseconds. Remarks A Date object contains a number representing a particular instant in time to within a millisecond. If the value of an argument is greater than its range or is a negative number, other stored values are modified accordingly. For example, if you specify 150 seconds, JScript redefines that number as two minutes and 30 seconds. If the number is NaN, the object does not represent a specific instant of time. If you pass no parameters to the Date object, it is initialized to the current time (UTC). A value must be given to the object before you can use it. The range of dates that can be represented in a Date object is approximately 285,616 years on either side of January 1, 1970. The Date object has two static methods that are called without creating a Date object. They are parse and UTC. Error The following example illustrates the use of the Date object. function DateDemo(){
Date Object
1
2
Date Object var d, s = "Today's date is: "; d = new Date(); s += (d.getMonth() + 1) + "/"; s += d.getDate() + "/"; s += d.getYear(); return(s);
//Declare variables. //Create Date object. //Get month //Get day //Get year. //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 | toGMTString Method | 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
Global Object An intrinsic object whose purpose is to collect global methods into one object. The Global object has no syntax. You call its methods directly. Remarks The Global object is never used directly, and cannot be created using the new operator. It is created when the scripting engine is initialized, thus making its methods and properties available immediately. Properties 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
2
Global Object
2
Global Object
Math Object An intrinsic object that provides basic mathematics functionality and constants. Math.[{property | method}]
Arguments property Required. Name of one of the properties of the Math. object. method Required. Name of one of the methods of the Math. object. Remarks The Math object cannot be created using the new operator, and gives an error if you attempt to do so. The scripting engine creates it when the engine is loaded. All of its methods and properties are available to your script at all times. Properties E Property | LN2 Property | LN10 Property | LOG2E Property | LOG10E Property | PI Property | SQRT1_2 Property | SQRT2 Property Methods abs Method | acos Method | asin Method | atan Method | atan2 Method | ceil Method | cos Method | exp Method | floor Method | log Method | max Method | min Method | pow Method | random Method | round Method | sin Method | sqrt Method | tan Method Requirements Version 1 See Also Number Object
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
Math Object
1
2
Math Object
2
Math Object
Regular Expression Object An object that contains a regular expression pattern along with flags that identify how to apply the pattern. Syntax 1 re = /pattern/[flags]
Syntax 2 re = new RegExp("pattern",["flags"])
Arguments re Required. The variable name to which the regular expression pattern is assigned. pattern Required. The regular expression pattern to use. If you use Syntax 1, delimit the pattern by "/" characters. If you use Syntax 2, enclose the pattern in quotation marks. flags Optional. Enclose flag in quotation marks if you use Syntax 2. Available flags, which may be combined, are: • g (global search for all occurrences of pattern) • i (ignore case) • m (multiline search) Remarks The Regular Expression object should not be confused with the global RegExp object. Even though they sound the same, they are separate and distinct. The properties of the Regular Expression object contain only information about one particular Regular Expression instance, while the properties of the global RegExp object contain continually updated information about each match as it occurs. Regular Expression objects store patterns used when searching strings for character combinations. After the Regular Expression object is created, it is either passed to a string method, or a string is passed to one of the regular expression methods. Information about the most recent search performed is stored in the global RegExp object. Use Syntax 1 when you know the search string ahead of time. Use Syntax 2 when the search string is changing frequently, or is unknown, such as strings taken from user input. The pattern argument is compiled into an internal format before use. For Syntax 1, pattern is compiled as the script is loaded. For Syntax 2, pattern is compiled just before use, or when the compile method is called. Example The following example illustrates the use of the Regular Expression object by creating an object (re) containing a regular expression pattern with its associated flags. In this case, the resulting Regular Expression object is then used by the match method: function MatchDemo(){ var r, re; //Declare variables. var s = "The rain in Spain falls mainly in the plain"; re = new RegExp("Spain","i"); //Create regular expression object. r = s.match(re); //Find a match within string s.
Regular Expression Object
1
2
Regular Expression Object 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
String Object Allows manipulation and formatting of text strings and determination and location of substrings within strings. Syntax newString = new String(["stringLiteral"])
Arguments newString Required. The variable name to which the String object is assigned. stringLiteral Optional. Any group of Unicode characters. Remarks String objects can be created implicitly using string literals. String objects created in this fashion (referred to as standard strings) are treated differently than String objects created using the new operator. All string literals share a common, global string object. If a property is added to a string literal, it is available to all standard string objects: 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 of members. 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 | concat Method | fixed Method | fontcolor Method | fontsize Method | fromCharCode Method | indexOf Method | italics Method | lastIndexOf Method | link Method | match Method | replace Method | search Method | slice Method | small Method | split Method | strike Method | sub Method | substr Method | substring Method | sup Method | toLowerCase Method | toUpperCase Method | toString Method | valueOf Method
String Object
1
2
String Object
Requirements Version 1 See Also new Operator
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
2
String Object
Addition Assignment Operator (+=) Adds the value of an expression to the value of a variable and assigns the result to the variable. result += expression
Arguments result Any variable. expression Any expression. Remarks 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 Both expressions are numeric or Boolean Both expressions are strings One expression is numeric and the other is a string Requirements
Then Add Concatenate Concatenate
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
2
Addition Assignment Operator (+=)
2
Addition Assignment Operator (+=)
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 the variable. result &= expression
Arguments result Any variable. expression Any 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 AND operation on them. The output of this operation behaves like this: 0101 1100 ---0100
(result) (expression) (output)
Any time both of the expressions have a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a 0 in that digit. Requirements Version 1 See Also & Operator | Operator Precedence | Operator Summary
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
Bitwise AND Assignment Operator (&=)
1
2
Bitwise AND Assignment Operator (&=)
2
Bitwise AND Assignment Operator (&=)
Bitwise AND Operator (&) Performs a bitwise AND on two expressions. result = expression1 & expression2
Arguments result Any variable. expression1 Any expression. expression2 Any expression. Remarks The & operator looks at the binary representation of the values of two expressions and does a bitwise AND operation on them. The result of this operation behaves as follows: 0101 1100 ---0100
(expression1) (expression2) (result)
Any time both of the expressions have a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a 0 in that digit. Requirements Version 1 See Also &= Operator | Operator Precedence | Operator Summary
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
Bitwise AND Operator (&)
1
2
Bitwise AND Operator (&)
2
Bitwise AND Operator (&)
Bitwise Left Shift Operator ( 2
Requirements Version 1 See Also >= 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
2
Bitwise Right Shift Operator (>>)
2
Bitwise Right Shift Operator (>>)
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 result Any variable. expression Any 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 bitwise exclusive OR operation on them. The result of this operation behaves as follows: 0101 1100 ---1001
(result) (expression) (result)
When one, and only one, of the expressions has a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a 0 in that digit. Requirements Version 1 See Also ^ Operator | Operator Precedence | Operator Summary
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
Bitwise XOR Assignment Operator (^=)
1
2
Bitwise XOR Assignment Operator (^=)
2
Bitwise XOR Assignment Operator (^=)
Bitwise XOR Operator (^) Performs a bitwise exclusive OR on two expressions. result = expression1 ^ expression2
Arguments result Any variable. expression1 Any expression. expression2 Any expression. Remarks The ^ operator looks at the binary representation of the values of two expressions and does a bitwise exclusive OR operation on them. The result of this operation behaves as follows: 0101 1100 ---1001
(expression1) (expression2) (result)
When one, and only one, of the expressions has a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a 0 in that digit. Requirements Version 1 See Also ^= Operator | Operator Precedence | Operator Summary
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
Bitwise XOR Operator (^)
1
2
Bitwise XOR Operator (^)
2
Bitwise XOR Operator (^)
Comma Operator (,) Causes two expressions to be executed sequentially. expression1, expression2
Arguments expression1 Any expression. expression2 Any expression. Remarks The , operator causes the expressions on either side of it to be executed in left-to-right order, and obtains the value of the expression on the right. The most common use for the , operator is in the increment expression of a for loop. For example: 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 the restriction. 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
2
Comma Operator (,)
2
Comma Operator (,)
Comparison Operators Returns a Boolean value indicating the result of the comparison. expression1 comparisonoperator expression2
Arguments expression1 Any expression. comparisonoperator Any comparison operator. expression2 Any expression. Remarks When comparing strings, JScript uses the Unicode character value of the string expression. The following describes how the different groups of operators behave depending on the types and values of expression1 and expression2: 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, or Boolean. • NaN is not equal to anything including itself. • Negative zero equals positive zero. • null equals both null and undefined. • Values are considered equal if they are identical strings, numerically equivalent numbers, the same object, identical Boolean values, or (if different types) they can be coerced into one of these situations. • Every other comparison is considered unequal. Identity (===, !==) These operators behave identically to the equality operators except no type conversion is done, and the types must be the same to be considered equal. Requirements Version 1
Comparison Operators
1
2
Comparison Operators
See Also Operator Precedence | Operator Summary
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
2
Comparison Operators
Conditional (Ternary) Operator (?:) Executes one of two statements depending on a condition. test ? statement1 : statement2
Arguments test Any Boolean expression. statement1 A statement executed if test is true. May be a compound statement. statement2 A statement executed if test is false. May be a compound statement. Remarks The ?: operator is a shortcut for an if...else statement. It is typically used as part of a larger expression where an if...else statement would be awkward. For example: 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 an if...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
2
Conditional (Ternary) Operator (?:)
2
Conditional (Ternary) Operator (?:)
delete Operator Deletes 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 allow it 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
2
delete Operator
2
delete Operator
Division Assignment Operator (/=) Divides the value of a variable by the value of an expression and assigns the result to the variable. result /= expression
Arguments result Any numeric variable. expression Any numeric expression. Remarks 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
2
Division Assignment Operator (/=)
2
Division Assignment Operator (/=)
Increment (++) and Decrement ( ) Operators Increments or decrements the value of a variable by one. Syntax 1 result result result result
= = = =
++variable --variable variable++ variable--
Syntax 2 ++variable --variable variable++ variable--
Arguments result Any variable. variable Any variable. Remarks The increment and decrement operators are used as a shortcut to modify the value stored in a variable. The value of an expression containing one of these operators depends on whether the operator comes before or after the variable: var j, k; k = 2; j = ++k;
j is assigned the value 3, as the increment occurs before the expression is evaluated. 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
2
Increment (++) and Decrement ( ) Operators
Build: Topic Version 5.6.9309.1546 JScript
2
Increment (++) and Decrement ( ) Operators
instanceof Operator Returns a Boolean value that indicates whether or not an object is an instance of a particular class. result = object instanceof class
Arguments result Required. Any variable. object Required. Any object expression. class Required. Any defined object class. Remarks The instanceof operator returns true if object is an instance of class. It returns false if object is not an instance of the specified class, or if object is null. Example 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
2
instanceof Operator
Build: Topic Version 5.6.9309.1546 JScript
2
instanceof Operator
Left Shift Assignment 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
2
Right Shift Assignment Operator (>>=)
2
Right Shift Assignment Operator (>>=)
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 result Any numeric variable. expression Any 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
2
Subtraction Assignment Operator (-=)
2
Subtraction Assignment Operator (-=)
typeof Operator Returns 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
2
typeof Operator
2
typeof Operator
Unsigned Right Shift Operator (>>>) Right shifts the bits of an expression, without maintaining sign. result = expression1 >>> expression2
Arguments result Any variable. expression1 Any expression. expression2 Any expression. Remarks The >>> operator shifts the bits of expression1 right by the number of bits specified in expression2. Zeroes are filled in from the left. Digits shifted off the right are discarded. For example: var temp temp = -14 >>> 2
The variable temp has a value of 1073741820 as -14 (11111111 11111111 11111111 11110010 in binary) shifted right two bits equals 1073741820 (00111111 11111111 11111111 11111100 in binary). Requirements Version 1 See Also >>>= Operator | > Operator | Operator Precedence | Operator Summary
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
Unsigned Right Shift Operator (>>>)
1
2
Unsigned Right Shift Operator (>>>)
2
Unsigned Right Shift Operator (>>>)
Unsigned Right Shift Assignment Operator (>>>=) Right shifts the value of a variable by the number of bits specified in the value of an expression, without maintaining sign, and assigns the result to the variable. result >>>= expression
Arguments result Any variable. expression Any 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 are filled in from the left. Digits shifted off the right are discarded. For example: var temp temp = -14 temp >>>= 2
The variable temp has a value of 1073741820 as -14 (11111111 11111111 11111111 11110010 in binary) shifted right two bits equals 1073741820 (00111111 11111111 11111111 11111100 in binary). Requirements Version 1 See Also >>> Operator | > Operator | Operator Precedence | Operator Summary
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
Unsigned Right Shift Assignment Operator (>>>=)
1
2
Unsigned Right Shift Assignment Operator (>>>=)
2
Unsigned Right Shift Assignment Operator (>>>=)
void Operator Prevents 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 you want 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
2
void Operator
2
void Operator
0...n Properties Returns the actual value of individual arguments from an arguments object returned by the arguments property of an executing function. [function.]arguments[[0|1|2|...|n]]
Arguments function Optional. The name of the currently executing Function object. 0, 1, 2,
, n Required. Non-negative integer in the range of 0 to n where 0 represents the first argument and n represents the final argument. The value of the final argument n is arguments.length-1. Remarks The values returned by the 0 . . . n properties are the actual values passed to the executing function. While not actually an array of arguments, the individual arguments that comprise the arguments object are accessed the same way that array elements are accessed. Example The following example illustrates the use of the 0 . . . n properties of the arguments object. To fully understand the example, pass one or more arguments to the function: function ArgTest(){ var s = ""; s += "The individual arguments are: " for (n=0; n< arguments.length; n++){ s += ArgTest.arguments[n]; s += " "; } return(s); } print(ArgTest(1, 2, "hello", new Date()));
Requirements Version 5.5 See Also Applies To: arguments Object | Function object
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 JScript
0...n Properties
1
2
0...n Properties
2
0...n Properties
$1...$9 Properties Returns the nine most-recently memorized portions found during pattern matching. Read-only. RegExp.$n
Arguments RegExp Always the global RegExp object. n Any integer from 1 through 9. Remarks The value of the $1...$9 properties is modified whenever a successful parenthesized match is made. Any number of parenthesized substrings may be specified in a regular expression pattern, but only the nine most recent can be stored. 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
2
$1...$9 Properties
2
$1...$9 Properties
callee Property Returns the Function object being executed, that is, the body text of the specified Function object. [function.]arguments.callee
The optional function argument is the name of the currently executing Function object. Remarks The callee property is a member of the arguments object that becomes available only when the associated function is executing. The initial value of the callee property is the Function object being executed. This allows anonymous functions to be recursive. Example function factorial(n){ if (n tag from displaying the code. Since the example is a general function it is not tied to any particular form control you can include it in the HEAD section of the page: Place Your Order 2 End Function --> ...
You can use SCRIPT blocks anywhere in an HTML page. You can put them in both the BODY and HEAD sections. However, you will probably want to put all general-purpose scripting code in the HEAD section in order to keep all the code together. Keeping your code in the HEAD section ensures that all code is read and decoded before it is called from within the BODY section. One notable exception to this rule is that you may want to provide inline scripting code within forms to respond to the events of objects in your form. For example, you can embed scripting code to respond to a button click in a form: Test Button Events MsgBox "Button Pressed!"
Adding VBScript Code to an HTML Page
1
2
Adding VBScript Code to an HTML Page
Most of your code will appear in either Sub or Function procedures and will be called only when specified by your code. However, you can write VBScript code outside procedures, but still within a SCRIPT block. This code is executed only once, when the HTML page loads. This allows you to initialize data or dynamically change the look of your Web page when it loads.
© 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
A Simple VBScript Page A Simple Page With Microsoft® Internet Explorer, you can view the page produced by the following HTML code. If you click the button on the page, you see VBScript in action. A Simple First Page A Simple First Page
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 tags, recognizes there is a piece of VBScript code, and saves the code. When you click the button, Internet Explorer makes the connection between the button and the code, and runs the procedure. The Sub procedure in the 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 tag), and an event name, OnClick. The two names are joined by an underscore(_). Any time the button is clicked, Internet Explorer looks for and runs the corresponding event procedure, Button1_OnClick. Internet Explorer defines the events available for form controls in the Internet Explorer Scripting Object Model documentation, which can be found on the Microsoft® Web site (http://www.microsoft.com). Pages can use combinations of controls and procedures, too. VBScript and Forms shows some simple interactions between controls. Other Ways to Attach Code to Events Although the preceding way is probably the simplest and most general, you can attach VBScript code to events in two other ways. Internet Explorer allows you to add short sections of inline code in the tag defining the control. For example, the following tag performs the same action as the previous code example when you click the button:
Notice that the function call itself is enclosed in single quotation marks, and the string for the MsgBox function is enclosed in double quotation marks. You can use multiple statements as long as you separate the statements with colons (:). You can also write a tag so that it applies only to a particular event for a specific control:
A Simple VBScript Page
1
2
A Simple VBScript Page
Because the tag already specifies the event and the control, you don't use Sub and End Sub statements.
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Visual Basic Scripting Edition
2
A Simple VBScript Page
VBScript and Forms Simple Validation You can use Visual Basic Scripting Edition to do much of the form processing that you'd usually have to do on a server. You can also do things that just can't be done on the server. Here's an example of simple client-side validation. The HTML code is for a text box and a button. If you use Microsoft® Internet Explorer to view the page produced by the following code, you'll see a small text box with a button next to it.
Simple Validation 10 Then MsgBox "Please enter a number between 1 and 10." Else MsgBox "Thank you." End If Else MsgBox "Please enter a numeric value." End If End Sub--> Simple Validation objects. Internet Explorer also lets you exploit the full power 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
Using VBScript with Objects Using Objects Whether you use an ActiveX® control (formerly called an OLE control) or a Java object, Microsoft Visual Basic Scripting Edition and Microsoft® Internet Explorer handle it the same way. If you're using Internet Explorer and have installed the Label control, you can see the page produced by the following code. You include an object using the tags and set its initial property values using tags. If you're a Visual Basic programmer, you'll recognize that using the tags is just like setting initial properties for a control on a form. For example, the following set of and tags adds the ActiveX Label control to a page:
You can get properties, set properties, and invoke methods just as with any of the form controls. The following code, for example, includes controls you can use to manipulate two properties of the Label control:
With the form defined, an event procedure for the cmdChangeIt button changes the label text:
The code qualifies references to controls and values inside the forms just as in the Simple Validation example. Several ActiveX controls are available for use with Internet Explorer. You can find complete information about the properties, methods, and events there, as well as the class identifiers (CLSID) for the controls on the Microsoft® Web site (http://www.microsoft.com). You can find more information about the tag on the Internet Explorer 4.0 Author's Guide and HTML Reference page. Using VBScript with Objects
1
2
Using VBScript with Objects Note Earlier releases of Internet Explorer required braces ({}) around the classid attribute and did not conform to the W3C specification. Using braces with the current release generates a "This page uses an outdated version of the tag" message.
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Visual Basic Scripting Edition
2
Using VBScript with Objects
VBScript Language Reference Constants 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
2
VBScript Language Reference
2
VBScript Language Reference
Count Property Returns 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)) + ""; } 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) & "" ' Create return string. Next ShowKeys = s End 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
2
Count Property
2
Count Property
Item Property Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the specified key. Read/write. object.Item(key)[ = newitem]
Arguments object Required. Always the name of a collection or Dictionary object. key Required. Key associated with the item being retrieved or added. newitem Optional. Used for Dictionary object only; no application for collections. If provided, newitem is the new value associated with the specified key. Remarks If key is not found when changing an item, a new key is created with the specified newitem. If key is not found when attempting to return an existing item, a new key is created and its corresponding item is left empty. 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
2
Item Property
Scripting Runtime Library
2
Item Property
Key Property Sets a key in a Dictionary object. object.Key(key) = newkey
Arguments object Required. Always the name of a Dictionary object. key Required. Key value being changed. newkey Required. New value that replaces the specified key. Remarks If key is not found when changing a key, a new key is created and its associated item is left empty. 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
2
Key Property
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Scripting Runtime Library
2
Key Property
Add Method (Dictionary) Adds a key and item pair to a Dictionary object. object.Add (key, item)
Arguments object Required. Always the name of a Dictionary object. key Required. The key associated with the item being added. item Required. The item associated with the key being added. Remarks 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
2
Add Method (Dictionary)
2
Add Method (Dictionary)
Column Property Read-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.Column End 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
2
Column Property
2
Column Property
Line Property Read-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.Line End 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
2
Line Property
2
Line Property
Add Method (Folders) Adds a new folder to a Folders collection. object.Add (folderName)
Arguments object Required. Always the name of a Folders collection. folderName Required. The name of the new Folder being added. Remarks The following example illustrates the use of the Add method to create a new folder. [JScript] function AddNewFolder(path,folderName) { var fso, f, fc, nf; fso = new ActiveXObject("Scripting.FileSystemObject"); f = fso.GetFolder(path); fc = f.SubFolders; if (folderName != "" ) nf = fc.Add(folderName); else nf = fc.Add("New Folder"); } [VBScript] Sub AddNewFolder(path, folderName) Dim fso, f, fc, nf Set fso = CreateObject("Scripting.FileSystemObject") Set f = fso.GetFolder(path) Set fc = f.SubFolders If folderName "" Then Set nf = fc.Add(folderName) Else Set nf = fc.Add("New Folder") End If End Sub
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
2
Add Method (Folders)
2
Add Method (Folders)
Count Property Returns 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)) + ""; } 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) & "" ' Create return string. Next ShowKeys = s End 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
2
Count Property
2
Count Property
Script Components Microsoft® Windows® Script Components provide you with an easy way to create COM components using scripting languages such as Microsoft® Visual Basic® Scripting Edition (VBScript) and Microsoft® JScript®. Use script components as COM components in applications such as Microsoft® Internet Information Services (IIS), Microsoft® Windows® Script Host, and any other application that can support COM components. The areas discussed in this tutorial are shown in the following list. • Script Components Overview Learn what script components are and how to use them. • Creating Script Components Create a script component. • Using Script Components Use a script component in your applications. • Implementing ASP Script Components Create a script component that incorporates the functionality of Active Server Pages (ASP), allowing you to isolate and reuse ASP logic. • Implementing DHTML Behavior Script Components Create a script component that can be used in Microsoft® Internet Explorer 5.0 to define behaviors.
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Windows Script Components
Script Components
1
2
Script Components
2
Script Components
Script Components Overview Windows® Script Components are an exciting new technology that allows you to create powerful, reusable COM components with easy-to-use scripting languages such as Microsoft® Visual Basic® Scripting Edition (VBScript) and Microsoft® JScript®. The following topics provide an overview of script component technology, and explain how to create and use script components. • Introducing Script Components Learn what script components are, and the advantages to using them. • How Script Components Work Understand what script component technology consists of, and how to create script components.
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Windows Script Components
Script Components Overview
1
2
Script Components Overview
2
Script Components Overview
Introducing Windows Script Components Windows® Script Components provide you with an easy way to create powerful, reusable COM components in 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 Scripting Technologies Web site at www.microsoft.com. This new script component technology supports common types of COM components, such as Automation, and is extensible with add-ons such as DHTML behaviors. Script Components: • 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 performing middle-tier business logic, accessing and manipulating database data, adding transaction processing to applications, and adding interactive effects to a Web page using DHTML Behaviors. See Also 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
2
Introducing Windows Script Components
2
Introducing Windows Script Components
How Script Components Work Windows® Script Component technology consists of three pieces: • The script component run-time (Scrobj.dll), which helps dispatch COM requests to your scripts. In COM terms, Scrobj.dll functions as the inproc server for script components. • Interface handlers, which are compiled components that implement specific COM interfaces. Different interface handlers come ready to work as specific types of COM components. The most commonly used interface handlers, including the COM Automation interface handler, an ASP interface handler, and a handler for DHTML Behaviors, are already built into the script component run-time. Others are available as add-on components, or embedded into specific applications. • Your script component file (an .wsc file). Script component files are XML (Extensible Markup Language) files that contain information about what type of COM component you want to create (that is, what interface handlers you want to use). Then, depending on what functionality the handler makes available, you write script in your script component to implement those interfaces. The script component run-time serves as an entry point for the host application. The complexities of COM, including the implementation of such COM-standard interfaces as IUnknown, are embedded in the various interface handlers. Your script component contains only the script required to implement the functionality of the COM component. For example, one of the most common types of COM components is an Automation component, which is a component with properties and methods that can be called from other applications. The low-level COM interfaces required to implement this functionality such as dispatching to the correct function when a method is called are built into an Automation interface handler. In your script component file, you define the properties, methods, and events you want to expose, and the Automation handler makes sure they are called correctly when the host application needs them. See Also 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
2
How Script Components Work
2
How Script Components Work
Script Component File Contents Windows® 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 defining script components are not HTML tags, but are XML elements specifically used for script component definitions. A basic script component file contains these elements: • and elements The element encloses one entire script component definition. Multiple elements can appear in the same .wsc file, and are contained within a master element. • element Includes information used to register your script component as a COM component. This element might not be required if the host application (such as Microsoft® Internet Explorer 5.0) does not directly use the Windows registry when creating an instance of the script component. • element Encloses definitions for properties, methods, and events that your script component exposes. The definitions point to variables or functions defined in a separate block. • element Specifies the COM interface handler for the script component, which determines what type of COM component the script component will be. For example, by specifying , you implement the ASP interface handler and therefore get access to the ASP object model in your script component. The element is used to specify that a script component implements the COM Automation interface handler. Therefore, you don't need to create an element for the Automation handler. Note The script component run-time includes interface handlers for Automation (exposed using the element), for ASP, and for Internet Explorer 5.0 DHTML Behaviors. Other interface handlers are available as external DLLs. For more information about additional interface handlers and script components, see the Microsoft Scripting Technologies Web site. • element Contains the script used to implement the logic of your script component, depending on what type of COM component you are creating. For example, if you are creating a COM Automation component, you declare properties, methods, and events in a element, and then write the script to define them in one or more elements. • element Contains information about an object that you use in your script, such as another COM component. • elements Contain values that should not be hard-coded into script component code. Resource elements can include information that might change between versions, strings that might be translated, and other values. • element References a type library you want to use in script. • elements Contain text that is ignored when the script component is parsed and executed. Note If you are concerned that the .wsc files you create contain XML that conforms to XML standards, you can specify that the script component's XML parser check the XML syntax. For example, this is useful if you think you might someday use an XML editor to work with your files. Otherwise, however, it is not usually a concern. For more details, see Script Component Files and XML Conformance.
Script Component File Contents
1
2
Script Component File Contents
Skeleton Script Component File The following example illustrates how to construct a script component file. This skeleton shows how script component elements are assembled into a .wsc file. (interface-specific definitions here) element is optional in this example, because the file contains only one element. • The processing instruction includes attributes for specifying the error checking options. For details, see Checking For Errors in Script Component Files. If you do not include this element, the default options are all false. • A element can appear anywhere in the script component. • A element is not required in all cases. For example, a script component that implements the DHTML Behaviors interface handler in Internet Explorer 5.0 does not need to be registered, because Internet Explorer directly instantiates the behaviors as they are detected on the page. For details about registration requirements, see the documentation for the interface handler you are implementing, and note also which host the script component will be used in. • A element allows you to include a type library in the script component so you can use the library's constants in your script. • The element encloses , , and elements. The script that defines these appears later in the script component file. • The element is used to make available non-default COM interfaces. For example, you can expose the ASP interface with an type such as the following:
The exact elements that appear inside an element depend on what interface you are implementing. Note The element is shown here with an id attribute. However, this attribute is optional, except in cases where you must disambiguate objects or variables. For details, see the element. • In this skeleton, there are two script elements, one for VBScript and one for JScript. If you are using only one scripting language, you do not need more than one element. Because the declaration appears at the top of the file, a CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance. • The element creates a reference to an object you want to use in script within the script component. After creating the skeleton, fill in the elements to define the script component's functionality, depending on which interface handler you are implementing. See Also Checking For Errors in Script Component Files | Creating a Script Component Type Library | Creating Registration Information | Exposing Events | Exposing Methods | Exposing Properties | Implementing ASP Script Components | Implementing DHTML Behavior Script Components | Script Component Files and XML Conformance | Using the Script Component Wizard
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Windows Script Components Script Component File Contents
3
4
Script Component File Contents
4
Script Component File Contents
Using the Script Component Wizard The Windows® Script Component package includes a Script Component Wizard that automates the process of 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 scripting language you specify. • Prompts for methods you want to expose and creates the necessary elements in the scripting language you 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 the Microsoft Scripting Technologies Web site on www.microsoft.com. The wizard creates a skeleton script component with information you provide, and writes it out as an .wsc file. Edit the .wsc file and add your script to create the script component's functionality. Note The wizard creates a script component file containing the declaration at the top, meaning that the contents of the file must be XML-conformant. For more details, see Script Component Files and XML Conformance. See Also Script Component File Contents | Creating Registration Information | Creating Script Components | Script Component Files and XML Conformance
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Windows Script Components
Using the Script Component Wizard
1
2
Using the Script Component Wizard
2
Using the Script Component Wizard
Creating Registration Information If the host application requires it, you can register a Windows® Script Component as a COM component using a program such as Regsvr32.exe. Registration places information about the COM component in a public location (in Windows, registration information is stored in the Windows registry). By reading the registration information, applications can find and load the COM component. Note Registration is not required in every case. For example, a script component that implements the DHTML Behaviors interface handler in Internet Explorer 5.0 does not need to be registered, because Internet Explorer registers the behaviors as they are detected on the page. For more details about using Behaviors, see the "Using DHTML Behaviors" topic on the Microsoft Site Builder Network (SBN) Web site. If the host application supports monikers, you can also create an instance of a script component without registering it. 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 of the script component. For example, if your script component's program ID is Component.MyComponent, you can create an instance of it in Microsoft® Visual Basic® using a statement such as the following: Set Component = CreateObject("Component.MyComponent")
• A class ID, which is a GUID (globally unique ID) that uniquely identifies your script component. You can generate a GUID with a program such as Uuidgen.exe. Note If you create a script component using the Script Component Wizard, the wizard automatically creates a program ID and class ID for you. For details, see Using The Script Component Wizard. 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 is highly recommended that you provide a class ID for the script component yourself, to ensure that your script component has the same class ID on all computers on which it is registered. Allowing the registration program to create a class ID can also cause problems if you use the script component with development tools that store class IDs. If the registration creates a new class ID each time, it will not match the ID stored by the application. To create registration information for the script component • Create an element that includes at least a program ID, and optionally, a class ID, description, and version, as shown in the following example:
Note The registration attributes can appear in any order in the element.
Creating Registration Information
1
2
Creating Registration Information
Running Script During Registration The script component element also allows you to include script that will be executed when the script component is registered and unregistered. For example, you can post a message that the script component has been registered. To run script during registration and unregistration • In the element, include an element. To run script during registration, write a register( ) function. To run script when the script component has been unregistered, include an unregister( ) function. The following example shows how to post messages when the script component is registered or unregistered. Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance.
Registering for Remote Access If you are deploying your script component in a distributed environment, you can specify that the script component can be instantiated remotely. For example, you might be creating a script component designed to run on a server, but which will be called from code on a client. This scenario is possible if the client and server machines are properly configured with DCOM, which provides the mechanism for passing object pointers to the client from the server. To register a script component for remote access • Include the remotable attribute in the element, as shown in the following example:
For more details about creating instances of a script component remotely, see Using a Script Component in an Application.
2
Creating Registration Information
Creating Registration Information
3
See Also Script Component File Contents | Using The Script Component Wizard | Creating a Script Component Type Library | Checking For Errors in Script Component Files | Script Component Files and XML Conformance
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Windows Script Components
Creating Registration Information
3
4
Creating Registration Information
4
Creating Registration Information
Exposing Methods Methods are implemented as functions or subroutines in your Windows® Script Component file. To expose a method 1. Create a element as a child of the element. 2. In the element, include a element. The method element can optionally include one or more elements to define the method's parameters. 3. Write a procedure in any scripting language to implement the function. Place the procedure in a element outside the element but within the element. Be sure the function name matches the functionName, or if you did not specify a functionName, the methodName name you specified in the element. For example, the following example shows a fragment from a script component file with two methods, factorial and getRandomNumber. Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance. Function factorial(n) element, include a element that contains a element to define the read function and a element to define the write function. If you do not include the element, the property will be read-only. If you do not include the element, the property will be write-only. 2. Write procedures in a element outside the element to implement the functions. The function for setting the property's value the put function must accept a single parameter, the value to set the property to. The names of the procedures must match the internal names you specified in the element. If you did not specify an internalName attribute, the names of the functions must be the name of the function with the get_ prefix for a read function, and with a put_ prefix for the write function. 3. For example, the following script component fragment is an example of a script component file that exposes three properties: sname, dateOfBirth, and age. The dateOfBirth property is defined by Exposing Properties
1
2
Exposing Properties functions so it can include error checking. The age property is calculated, and is therefore defined as read-only. Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance. element, include the attribute dispid="0", as in the following example:
Note This technique can be used to assign either a default property or a default method, but not both. There can be only one element in the script component with the dispid of zero. See Also Exposing Events | Exposing Methods | Script Component File Contents | Script Component Files and XML Conformance
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Windows Script Components
Exposing Properties
3
4
Exposing Properties
4
Exposing Properties
Exposing Events To 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. For details, see Creating a Script Component Type Library. Note The Behavior handler exposes events in a slightly different way. For details, see Exposing Custom Events in Behavior Script Components.
Declaring Events Each event you want to be able to fire must be individually declared. To declare an event 1. Create a element as a child of the element. 2. In the element, include an element for each event you want to declare. 3. For example, the following script component fragment shows how to expose two events:
Specifying Dispatch Identifiers COM programming provides event notification via dispatch identifiers (each referred to as a dispid), which are integer values that identify a component's events. The dispid is compiled into the component's type library and 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 script component's events. However, if you prefer, you can specify your own dispids. Doing so allows you to: • Guarantee that events in your script component will always have the same dispid. If the type library generator assigns dispids, they can change each time the library is generated. • Map events in your script component to dispids with specific numbers. For example, if you want to fire a standard COM event such as an error notification, you can map your event to the values used by convention in COM. To specify a dispid for an event, include the dispid attribute in the element, as in the following example:
Dispids must be unique within the script component. You can specify a negative value for a dispid to map to conventional events, but must use only specified ranges, such as -999 to -500 for controls. For details about Exposing Events
1
2
Exposing Events
reserved dispid ranges, refer to documentation for DISPID in the MSDN library. Note The dispid number zero is used to identify a default method or property. For more details, see Exposing Methods and Exposing Properties.
Firing an Event You can fire an event by calling the fireEvent method, specifying the name of the event to fire. You cannot fire events that you did not expose in the element. You can fire an event in any script in your script component file. For example, the following illustrates how you can fire an event when a property value changes.
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
Creating a Script Component Type Library You can generate a type library for your Windows® Script Component containing information about its interfaces and members. In some host applications (such as Visual Basic), type libraries are necessary to enable events for the script component, while in other host applications, type libraries are optional. However, even if a type library is not required, generating one can make working with a script component easier and less error-prone in the host application. For example, if you are using Visual Basic as your host application, use the References dialog box to select a script component's type library. This allows you to bind events to the script component and make them visible in Visual Basic. In addition, when you are writing Visual Basic code that references the script component, Visual Basic uses the type library information in statement completion and in the Object Browser so you can easily see and use properties, methods, and events that the script component exposes. Note For information about using a type library in the host application, refer to the application's documentation. To create a script component type library • In Windows Explorer, right-click the script component .wsc file, and then choose Generate Type Library. A .tlb file is generated for the script component with the same name as the script component file, written to the folder where the .wsc file is, and registered in the Windows registry. For more precise control over generating type libraries, you can generate the type library dynamically from script inside the script component file, or you can use a command-line interface.
Generating Type Libraries Dynamically The script component run-time includes an Automation interface implemented by the Component.GenerateTypeLib object. You can use this object in script to generate a type library from within the script component file. This is particularly useful for creating a type library automatically when the script component is registered. To create a script component type library dynamically 1. In script inside the script component file, create an instance of the Component.GenerateTypeLib object by using syntax such as the following: set oTL = CreateObject("Scriptlet.GenerateTypeLib")
2. Set the following properties of the Component.GenerateTypeLib object: Property/Method Description AddURL (Method) Adds the URL of the script component file from which to generate the type library. You can call this method property multiple times 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 the name of the script component file with a .tlb extension. If the object is unable to create the specified library, it defaults to creating a type library called component.tlb. Doc (Property) A string containing any information that is stored in the
Creating a Script Component Type Library
1
2
Creating a Script Component Type Library
GUID
registry with the type library information. (Property) A GUID for the type library. (This is not the GUID for the script component.) If you do not provide one, the GenerateTypeLib object will create one, but then the type library will have a different GUID on each machine. The GUID must be exactly 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 is displayed in some applications, such as the Visual Basic Object Browser. MajorVersion (Property) An integer value you assign. MinorVersion (Property) An integer value you assign. 3. Call the type library object's Write method to create the .tlb file, then register it. 4. If you want to create an additional type library, call the GenerateTypeLib object's Reset method to clear the list of script component files in the AddURL property, reset the URLs and any other properties you want, and then call the Write method again. For example, the following script in a element creates a type library dynamically. Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance.
Command-line Interface If you are comfortable using the Command Prompt window, you can call the Rundll32.exe program to create 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
Creating a Script Component Type Library
3
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, with values as described under the previous section, To create a script component type library dynamically. -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 script component MyComponent.wsc (the command is wrapped for clarity): rundll32.exe c:\winnt\system32\scrobj.dll,GenerateTypeLib -name:MyComponentTLib -file:d:\components\MyComponent.tlb -doc:\"Sample component typelib\" -guid:{a1e1e3e0-a252-11d1-9fa1-00a0c90fffc0} -major:1 -minor:0 -URL:d:\components\MyComponent.wsc
Troubleshooting Type Libraries The process of generating a type library can fail for various reasons. The error you see might not be clear enough 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 of arguments with the same names. For details, see Exposing Properties. Note It is possible to define a script component in which the get and put property functions have different numbers of arguments, but you cannot create a type library for that script component. • If you are exposing events, you cannot use the same dispatch identifiers (dispid) more than once in a script component. Additionally, you cannot use a negative value for the dispid unless it is within a specified range. For details, see Exposing Methods. • The ID attributes of elements in the script component must be unique. If you are generating a type library from more than one script component, then the IDs must be unique in the type library as a whole. See Also Script Component File Contents | Creating Registration Information | Checking For Errors in Script Component Files | Script Component Files and XML Conformance
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Creating a Script Component Type Library
3
4
Creating a Script Component Type Library
Windows Script Components
4
Creating a Script Component Type Library
Referencing Other Components Your Windows® Script Component can include references to external components that you need to create the script 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's scripts.
Referencing Additional COM Components In your script component, it might be necessary to create instances of other COM components as needed. You can do so in two ways: • In script Create instances of other objects directly in your script. For example, you can use the CreateObject function in Microsoft® Visual Basic® Scripting Edition (VBScript) or the new ActiveXObject Object in JScript. • Using an OBJECT element Use an element similar to the tag you use in HTML pages. Using an element makes objects globally available to any script and allows scripting tools to provide statement completion. It also provides a convenient way to summarize and document the objects you use in your script component. Note Although elements in script components are similar to tags in HTML pages, the list of attributes for an element in a script component is shorter, because script components do not present a user interface. To create an OBJECT element • Create an element. This element should be inside the element, but outside of any other element such as a element. The following example shows an object definition in a script component.
Referencing an External Type Library Many components that you might work with support type libraries, which provide a complete listing of the component's classes and their members. By referencing the component's type libraries, you can use constants defined in the type library. To include a reference to a type library • Include a element in your script component that specifies the location and name of the type library to include. For example:
Referencing Resources Resource elements can include information that might change between versions, strings that might be Referencing Other Components
1
2
Referencing Other Components
translated, and other values. To reference resources 1. In the script component, but outside of the and elements (and element, if any), create one element for each resource you want to define, giving each element a unique ID. The following example shows two elements: Note A CDATA section is required to make the contents of the element opaque to the parser. For details, see Script Component Files and XML Conformance.
2. In your script, include the resource text or number by calling the getResourcefunction, as shown in the following example. Note A CDATA section is required to make the script in the element opaque to the parser. For details, see Script Component Files and XML Conformance.
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
Referencing Another Script Component in the Same Package You can create a package that contains multiple Windows® Script Components, so you can also instantiate and 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 a series of properties and methods. A second script component in the same package might implement the ASP interface, which provides access to the server object model for Microsoft® Internet Information Services (IIS). You can then create a method or property in the Automation script component that exposes the ASP script component and makes its members available. To reference one script component from another, create a skeleton member a property or method in one method that exposes the second script component. To reference another script component in the same script component file 1. Declare a property or method in the first script component. 2. 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 script component, the math method simply references the second script component, which exposes the add method and the multiply method. Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance.
Referencing Another Script Component in the Same Package
1
2
Referencing Another Script Component in the Same Package
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 script component. If you need to preserve instance information between calls, store the pointer to the second script component in a global variable, as in the following example. Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance. (Component2 as in previous example)
See Also Script Component File Contents | |
© 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
Checking For Errors in Script Component Files Because 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 component file, a generic error message is displayed. By specifying error notification, you can have the script component parser display details about the error. • Allow debugging. By default, you cannot use the script debugger for script components. If you enable debugging, you can launch the script debugger in response to an error, by setting a breakpoint, or with a Stop (Microsoft® Visual Basic® Scripting Edition (VBScript)) or debugger (JScript) statement.
Setting Error Options Specify error options as attributes of the XML processing instruction. To specify error checking • Include the processing instruction at the top of the script component file (but after the optional declaration) with one or more of the following attributes: • error Set this to true to display detailed error messages for syntax or run-time errors in the script component. • debug Set this to true to enable debugging. If this debugging is not enabled, you cannot launch the script debugger for a script component in any way. For example, the following enables all three error reporting options:
Tip Turn error reporting off before deploying your script component to a production environment. See Also Script Component File Contents | Using The Script Component Wizard | Creating Registration Information | Creating a Script Component Type Library | Script Component Files and XML Conformance
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Windows Script Components
Checking For Errors in Script Component Files
1
2
Checking For Errors in Script Component Files
2
Checking For Errors in Script Component Files
Using a Script Component in an Application After creating a Windows® Script Component, you can use it as you would any COM component, by calling it from a host application such as Microsoft® Visual Basic®, C++, Microsoft® Internet Explorer, or other applications. Note Script components written for DHTML Behaviors are instantiated differently than traditional COM objects. For details, see Using DHTML Behaviors on the Microsoft Site Builder Network (SBN) Web site. There are a variety of options for creating an instance of the script component, depending on the host application, the type of script component you are using, and where the script component is deployed. The primary difference, however, is whether you want to create an instance of the script component locally (on the same computer as the application) or remotely (on another computer). In either case, there are a few points to bear in mind. If you create an instance of the script component and change the .wsc file while using that instance, your instance of the component is not updated. To update it, create a new instance of the script component. The exact properties and methods you can use are defined by the element and by scripts in the script component file. If you are working in an environment that supports statement completion, such as Visual Basic, you can see a script component's properties and methods if you generate and use a type library. For details, see Creating a Script Component Type Library. If your attempt to create an instance of the script component fails, a likely cause is a syntax or run-time error in the script component file. A parsing error in any XML element (including the element) can cause the instantiation to fail. While you are developing your script component file, set error checking options in the processing instruction as described in Checking For Errors in Script Component Files. Tip To make it easier for the host application to know about the COM interfaces exposed by a script component, the script component run-time can generate a type library, which contains information about the properties, methods, and events available in the script component. For details, see Creating a Script Component Type Library.
Creating Local Instances of Script Components If the script component is installed on the same computer as the host application, you can register the script component as its own component as described in Registering a Script Component. You can then use the host application'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 ID Component.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 the script component, you must bind the object early with a Dim statement that includes the WithEvents keyword, such as the following: Dim WithEvents scMyComponent As MyComponent Private Sub Command1_Click() Set scMyComponent=CreateObject("MyComponent") End Sub
Using a Script Component in an Application
1
2
Using a Script Component in an Application Note For details, see Handling Script Component Events in the Host Application. This is not necessary if you do not intend to write handlers for script component events.
On a Web page, you can use the tag to create an instance of the script component. You must know the class ID of the script component and include it in the tag, as in the following example:
If the script component is not registered on the local computer, you can use the script component moniker to create an instance of it. The moniker is supported in functions such as GetObject. The script component run-time, Scrobj.dll, must be registered on the local computer. Note The GetObject function is not supported for script components in Microsoft® Internet Explorer for security reasons. For example, the following illustrates how to call the Visual Basic GetObject function to create an instance of an unregistered script component: 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 script component to instantiate by adding its name to the file name with a hash mark (#) as a delimiter. The following creates an instance of the script component whose ID is "math" contained in the file MyComponent.wsc: 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 another computer, such as a Web server. Use a complete URL (with HTTP protocol) as the location for the script component, as in the following example: Set oComponent = GetObject("script:http://myserver/MyComponent.wsc")
Internet Explorer 5.0 supports DHTML Behavior syntax for creating instances of script components, which works somewhat differently than the traditional syntax for instantiating objects and will ensure that the script component cannot access potential unsafe system objects. For an example, see Using DHTML Behaviors on the Microsoft Site Builder Network (SBN) Web site.
Creating Remote Instances of Script Components If the remotable attribute of a script component's element has been set to "true," the script component 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 is running any of the following: • Windows NT 4.0 • Windows 95 running Internet Explorer 4.0 • Windows 95 with the OEM Service Release 2 (OSR2) or later. For details, see the Windows 95 OSR2 page on the Microsoft® Web site. • Windows 95 with DCOM for Windows 95, version 1.2. For details, see the DCOM for Windows 95 page on the Microsoft® Web site. 2
Using a Script Component in an Application
Using a Script Component in an Application
3
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 script component run-time (Scrobj.dll) at the time you instantiate the script component. However, you must have a reference to the remote script component in the local Windows registry for DCOM. For details, see Registering a Script Component. • On the remote computer, you require the script component and the script component runtime. Both must be registered. When you create an instance of a remote script component, it works within your application as if it were a local object; you call its methods and get and set its properties normally. However, the remote script component's script runs on the remote machine and has access to that machine's resources (within any limitations imposed by security, and so forth). Communication between the host application on the local machine and the script component on the remote machine is handled automatically and invisibly by DCOM. To create a remote instance of a script component, call the CreateObject method, passing it the name of the remote computer as a parameter. Note The ability to use CreateObject for instantiating remote script components requires Visual Basic 6.0 or later or VBScript 5.0 or later. The following Visual Basic example shows how to do this on a computer named "myserver": Set newS = CreateObject("Component.MyComponent", "myserver")
Note There can be a slight delay when you first instantiate a remote script component while DCOM establishes communication between the computers. See Also Creating Registration Information | Creating Script Components | How Script Components Work | Introducing Script Components | Registering a Script Component
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Windows Script Components
Using a Script Component in an Application
3
4
Using a Script Component in an Application
4
Using a Script Component in an Application
Handling Script Component Events in the Host Application Most 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 DHTML object model. For details, see Exposing Custom Events in Behavior Script Components. In Visual Basic, for example, you must use early (compile-time) binding to the component in order to receive events. Early binding requires a type library, so you must have generated a type library for the script component. For details, see Creating a Script Component Type Library. In addition, when you declare the object variable for the component, you must specify the WithEvents keyword. (The class name used in the Dim statement is the ID that you assigned in the script component's element.) An example in Visual Basic might look like this: Dim WithEvents Scriptlet1 as MyScriptlet Set 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
2
Handling Script Component Events in the Host Application
2
Handling Script Component Events in the Host Application
Creating a Behavior Script Component Creating a Behavior script component is similar to creating any other kind of script component, except that you 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 element that specifies the Behavior interface handler. Within the element, you use: • elements to bind events from the containing document to functions created in a separate element in the script component. • elements to define HTML text to be inserted into the containing document. • elements to define custom events that will be fired by the script component. Behavior script components can also include custom properties and methods that extend those already available for the element in the containing document. For details, see Exposing Properties and Methods in Behavior Script Components. The following example shows a Behavior script component that changes the color of an element in the containing page whenever the mouse is passed over the element. To do this, the sample binds the DHTML onmouseover and onmouseout events to functions in the script component that set the element's DHTML style attribute. The sample also sets the document's link color when the document is initialized by binding to the DHTML window object's onload event. In addition to binding events to script, the script component also inserts text into any elements in the containing document that are linked to this script component. Finally, it exposes and fires an event called onchange, which extends the DHTML window object's event object with a custom property called newvalue. Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance. 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. This will call the init function when the onload event of window is fired. The following defines HTML text that will appear in
Creating a Behavior Script Component
1
2
Creating a Behavior Script Component the containing document. This is the HTML to show in the element The following defines a custom event that is fired from within the script component by the fireEvent method.
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 the containing function, not to the element on which the event is being fired. • Just as in an HTML page, it is possible to place inline script within a in a script component. In this instance, the global variables normalColor and normalSpacing are defined in inline script. Note Inline script is executed even before the behavior is applied to the element, which limits what statements can be executed in inline script. For example, if the same behavior in the example exposed a property called hiliteColor, the inline script could refer to hiliteColor directly (in other words, it resolves against the script component's namespace). It is illegal, however, to refer to hiliteColor as Behavior.element.hiliteColor from an inline script, because at that point, the behavior has not yet been applied to the element. For more information, see Scope Rules and Timing Considerations later in this topic.
Behavior-Related Enhancements to the DHTML Object Model The following enhancements were made to the DHTML object model for Microsoft® Internet Explorer 5 in order to add support for behaviors. 2
Creating a Behavior Script Component
Creating a Behavior Script Component
3
• 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 receive event notifications from the containing page, by specifying a function that gets called whenever the event 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 needs to 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 event object is accessible to event handlers through the DHTML window object, in a behavior script component the event object is passed in as a parameter to the event handler. The following code from a hypothetical calculator script component demonstrates keyboard and mouse events bound to a script component function called doCalc. The doCalc function uses the event object to get information about the conditions under which the event was fired. Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance.
Scope Rules When working with script components, you actually work with three namespaces: the behavior, the element, and the containing document. Scope rules define the order in which name conflicts are resolved in a behavior script component. A name will be resolved in this order: The name is resolved to one defined by the behavior anywhere in the script component, whether a variable, a behavior-defined property, a method, or an event. If the name is not resolved successfully, it is resolved to a property, method, or event that applies to the element. Finally, the name is resolved to the name of a property, method, or event that applies to the window object in the containing page. Creating a Behavior Script Component
3
4
Creating a Behavior Script Component
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.
Timing Considerations When creating behaviors, it is important to know when the behavior is applied to the element. Until the behavior has been applied, scripts cannot have access to the values of behavior-defined properties that might be set in the document. Because the behavior is encapsulated in a separate file from the HTML document, it is downloaded separately from the rest of the document. As the document and behavior are parsed and loaded, the behavior receives notifications of progress through the function specified with the attachNotification method. Currently, the behavior is notified with a "contentChange" or a "documentReady" notification. The "contentChange" notification is sent when the content of the element to which the behavior has been attached has been parsed, and any time thereafter that the content of the element is changed. The "documentReady" notification is sent when the document has been downloaded and parsed. Because inline script in the script component file is executed as soon as the behavior is instantiated, the values of behavior-defined attributes and properties that are being set in the document may not be accessible from an inline script. However, these properties will be available as soon as the first "contentChange" notification is sent. See Also Exposing Properties and Methods in Behavior Script Components | Exposing Custom Events in Behavior Script Components | Behavior Handler Reference
© 2001 Microsoft Corporation. All rights reserved. 4
Creating a Behavior Script Component
Creating a Behavior Script Component
5
Build: Topic Version 5.6.9309.1546 Windows Script Components
Creating a Behavior Script Component
5
6
Creating a Behavior Script Component
6
Creating a Behavior Script Component
Exposing Properties and Methods in Behavior Script Components Behavior script components can expose custom properties and methods in a manner similar to Automation script components. Behavior script component properties and methods extend the properties and methods available to elements in the containing page. For example, you might create a behavior script component that changes the color of an element when the mouse is passed over it. By defining a property in the script component, you can make available a custom property in the document, perhaps called hiliteColor, that allows 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 as that which is already defined for the element. Properties and methods are defined in a element separate from the element used to specify the Behavior handler. For details, see Exposing Properties and Exposing Methods.
Exposing a Property Properties are exposed in a element, as in any script component. The following script component fragment shows a Behavior script component that exposes the custom property hiliteColor. If the containing page does not specifically set the property's value, the default is set to "red." Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance.
Exposing a Method Exposing a method in a Behavior script component is identical to doing so in an Automation script component. For details, see Exposing Methods. In a Behavior script component, methods exposed in the script component extend those already available for the element in the containing document. See Also Exposing Custom Events in Behavior Script Components
Exposing Properties and Methods in Behavior Script Components
1
2
Exposing Properties and Methods in Behavior Script Components
© 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
Exposing Custom Events in Behavior Script Components Behavior script components, like Automation script components, can expose custom events that are fired inside the script component and can be handled in the containing document. An event is declared in the element as in the following:
The event can then be fired by calling the fireEvent method in script: // Other code here. fireEvent("onResultChange"); // Other code here.
A behavior can override an element's default behavior by exposing an event of the same name as one that is already defined for the element. For example, a behavior that exposes an onclick event can override the element's default onclick event.
Getting and Setting Custom Event Information Your custom script component event can get access to the DHTML event object, which maintains event-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 event back to the containing event. In your script component code, call the createEventObject method to create a new instance of an event object, and then set one or more properties on the new event object. When you call the fireEvent method, you can pass the new event object with the event name. To create a new expando property, simply name it when assigning its value in your script. The following shows how you can create a new property called myprop for the event object: oEvent = createEventObject(); oEvent.myprop = "a new value"
Note You can create expando properties only if you are using Microsoft® JScript® (or JavaScript). This feature is not supported in Microsoft® Visual Basic® Scripting Edition (VBScript).
Example The following script component fragment is derived from a calculator script component sample. The sample defines a custom onResultChange event that is fired to the containing document whenever the result changes. Event-specific information (the actual calculation result) is passed via the expando property called result. Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance. Exposing Custom Events in Behavior Script Components
1
2
Exposing Custom Events in Behavior Script Components
The following shows what the containing page looks like. When the onResultChange event fires, the results of the calculation are extracted from expando property result of the DHTML window.event object and displayed in the resultWindow element. LK\:CALC {behavior:url(calc.wsc)} function showResults(){ resultWindow.innerText=window.event.result; } 0.
See Also Exposing Properties and Methods in Behavior Script Components
© 2001 Microsoft Corporation. All rights reserved. 2
Exposing Custom Events in Behavior Script Components
Exposing Custom Events in Behavior Script Components
3
Build: Topic Version 5.6.9309.1546 Windows Script Components
Exposing Custom Events in Behavior Script Components
3
4
Exposing Custom Events in Behavior Script Components
4
Exposing Custom Events in Behavior Script Components
Element Specifies additional COM interface handlers for a script component. handler-specific information here
Values COMHandlerName The name of the interface handler to reference. Interface handlers are usually implemented as DLLs, which you must be sure are available and registered in the production environment for your script component. Some handlers, such as the Automation and ASP handlers, are built into the script component run-time (Scrobj.dll). Examples of available interface handlers include: Interface handler Description How implemented ASP Allows a script component to Built into Scrobj.dll get access to the Microsoft Internet Information Services (IIS) Active Server Pages (ASP) object model. Built into Scrobj.dll DHTML Behaviors Allows a behavior script component to communicate with the containing page so it can fire events and access the DHTML object model. internalName (Optional) A name you can use to reference the handler in your script. By default, properties, methods, events, and other members of a script component are available in the global namespace. However, if there is a naming conflict between elements, the names can be disambiguated by prefixing them with the ID of the element to which they belong, as in the following: [...] [...] // [...] sctBehavior.fireEvent("onResultChange",oEvent);
fAssumed (Optional) A Boolean flag indicating that the internalName is assumed in scripts. The default value for this attribute is true, and members of the object model exposed by the handler are added to the global script namespace and can be accessed unqualified. You only need to include this attribute if you want to set it to false and therefore hide members of a specific 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 Element
1
2
Element
interface). The Automation object's properties, methods, and events are defined in the script component's element. Because the Automation handler is implemented by default, you do not need to implement it with the element. Script components can also implement additional COM interfaces by including an element. Inside the 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 and elements that are specific to the DHTML Behavior interface. Example
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
Element
Element Declares a property.
or
Values propertyName The name of the property to expose. Unless you specify an internalName attribute, this name must match the name of a global variable that will be used to hold the property's value. propertyVariable (Optional) The name of the global variable in the scriptlet file's element that will hold the value for propertyName. If you do not include the internalName attribute, the property value is maintained in a variable named the same as propertyName. Specifying the internalName attribute allows you to use different names for the property and its corresponding global variable. getFunctionName (Optional) The name of a procedure that is used to read the value of the property. If you include element but no element, the property will be read-only. If you include a element but do not specify an internalName attribute, the method used to read the property value must have the name of the property plus the get_ prefix (for example, get_lastname). putFunctionName (Optional) The name of a procedure that is used to write the value of the property. If you include a element but no element, the property will be write-only. If you include a element but do not specify an internalName attribute, the method used to read the property value must have the name of the property plus the put_ prefix (for example, put_lastname). Tip In XML, you can implement elements that have no content (such as the element) by closing the element with />. Remarks Properties can be exposed as simple values. In that case, the property is treated as a global variable inside the script component file. You can also implement properties as procedures (functions or subroutines), which allows you to calculate a property value and to control whether a property is read-only, read-write, or write-only. In this technique, properties are implemented as a procedure (function or subroutine) in a separate element. The element maps the name of the property to the procedures used to implement it. The names of the procedures must match the internal names you specified in the element. When putFunctionName is called, it is passed one argument that contains the value to which to set the property. In addition to the standard syntax shown above, you can use a shorthand notation to specify information what would otherwise be added using child tags. For example, if you want to declare a property with a "get" and "put" accessor of the same name as the property, you can use the following syntax:
Element
1
2
Element
which is functionally equivalent to:
If you wanted to explicitly name those accessors differently from the default, you can use the following syntax:
To specify a default property, include the attribute dispid="0" in the element. For details, see Exposing Properties. Example The following script component fragment shows the definition for four properties (sname, age, dateOfBirth, and mstatus). The sname property is a simple value. The age property is read-only, and is implemented with the function readAge. The dateOfBirth property is read-write, and is implemented wih the functions readDOB and writeDOB. Finally, the mstatus property is implemented with the default functions get_mstatus and put_mstatus. Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance. Element
Element
3
Function readAge() ' Calculates read-only age property. If isDate(gDOB) Then dobM = DatePart("m", gDOB) dobD = DatePart("d", gDOB) dobY = DatePart("yyyy", gDOB) todayY = DatePart("yyyy", Date) age = todayY - dobY ' 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 If End Function Function get_mstatus() ' Reads value of mstatus property. get_mstatus = gMStatus End Function Function put_mstatus(s) ' Writes value of mstatus property. If s = "M" Or s = "S" Then gMStatus = s Else gMStatus = "?" End If End Function ]]>
See Also Element | Element | Exposing Events | Exposing Methods | Exposing Properties
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Windows Script Components
Element
3
4
Element
4
Element
Element Encloses the script component's property, method, and event declarations.
See Also Element | Element | Element | Exposing Events | Exposing Methods | Exposing Properties
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Windows Script Components
Element
1
2
Element
2
Element
Element Includes a reference to an external type library.
Values progID The program ID from which the type library can be derived, which can include a version number (for example, ADO.Recordset.2.0). This can include the explicit program ID of a type library, or the program ID of the executable (such as a .DLL) that incorporates the type library. If you use the object attribute, you do not need to specify a version attribute, because the version can be inferred from the program ID. If the object attribute is specified, you cannot also specify a guid attribute. typelibGUID The GUID of the type library to reference. If the guid attribute is specified, you cannot also specify an object attribute. version (Optional) The version number of the type library to use. It must be in the form [.]. If a version is not specified, the default version is 1.0. If the object attribute is used to specify the type library and the version is not specified, the version is derived from the Registry key for the specified program ID. If none can be found, the default is 1.0. Remarks Referencing a type library in your script component allows you to use constants defined in the type library in scripts. The element looks up and makes available the type library associated with a specific program ID or type library name. Type library information can be available in .tlb, .olb, or .dll files. The element should appear inside the element. If there is more than one script component in the package, the type library applies to only the script component in whose element it is declared. Example In the following script component fragment, referencing the type library for ADO (contained in the file MSAD015.DLL) allows you to use ADO constants such as adStateOpen in your scripts. Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance. Element
1
2
Element
cnn.ConnectionString = "driver={SQL Server};server=myserver;uid=sa;database=pubs" cnn.Open If cnn.State = adStateOpen Then cnnState = "open" Else cnnState = "closed" End If End Function Function closeConnection() cnn.Close cnnState = "closed" End Function ]]>
See Also Referencing Other Components
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Windows Script Components
2
Element
Element Defines information used to register the script component as a COM component.
or (registration and unregistration script)
Values progID (Optional) A text name that programmers use to reference your script component when creating an instance of it. For example, if your script component's program ID is Component.MyComponent, you can create an instance of it in Microsoft® Visual Basic using a statement such as the following: Set Component = CreateObject("Component.MyComponent") Note Although a progid attribute is optional, you must include either a progid or a classid attribute (you can include both). If only the progid attribute is specified, the class ID is generated automatically. If only the class ID is created, then no progid is registered and the object can be created only by referencing the class ID directly. GUID (Optional) A GUID that you have generated using a class ID generation program (such as Uuidgen.exe). If you do not include a class ID, the registration program assigns a class ID to your script component. description (Optional) A text description of the script component that is stored in the registry and that is used in certain tools such as the Visual Basic object browser. version (Optional) A numeric version number that you assign. The version is appended to the program ID with a period (for example, MyComponent.1) when applications request a version-specific name. Use only numbers (decimal points are not allowed). Note The registration attributes can appear in any order in the element. remoteFlag (Optional) A Boolean value indicating whether the script component can be instantiated remotely using DCOM. For details, see Creating Remote Instances of Script Components in the topic "Using a Script Component in an Application." Remarks After a script component is created, it can be registered using a program such as Regsvr32.exe, which reads the information in the element and writes it into the computer's Windows Registry. For example, a script component can be registered this way: regsvr32 file:\\myserver\MyComponent.wsc
Element
1
2
Element Note A element is not required in all cases. For example, a script component that implements the DHTML Behaviors interface handler in Microsoft® Internet Explorer 5.0 does not need to be registered, because Internet Explorer registers the behaviors as they are detected on the page. For details about registration requirements, see the documentation for the interface handler you are implementing and note also which host the script component will be used in.
If you do not include class ID information, the registration program assigns a class ID to your script component at the time it is registered. However, the script component will have a different class ID everywhere it is registered. It is highly recommended that you provide a class ID for the script component yourself, to ensure that your script component has the same class ID on all computers on which it is registered. Allowing the registration program to create a class ID can cause problems if you use the script component with development tools that store class IDs. If the registration creates a new class ID each time, it will not match the the ID stored by the application. You can optionally run scripts when a script component is registered and unregistered. To do so, include a element within the 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 element that includes both a prog ID and a class ID.
The following registration element allows the script component to be instantiated via DCOM: progid="Component.TestScript" classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}" version="1" description="My Test Component" remotable=true/>
The following example shows a element that includes script to be run when the script component is registered and unregistered. Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance. version="1" description="My Test Component"> Function register() MsgBox "Component 'My Test Component' registered." End Function Function unregister() MsgBox "Component 'My Test Component' unregistered." End Function
2
Element
Element
3
]]>
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
Element
3
4
Element
4
Element
Element Isolates textual or numeric data that should not be hard-coded into the script component's scripts. text or number here
Values ResourceID A unique identifier for the resource within the script component. Remarks The element allows you to isolate strings or numbers in your script component that you want to intermingle with script in your script component. For example, resource elements are typically used to maintain strings that might be localized into another language. To get the value of a resource, call the getResource function, passing it the ID of the resource you want to use. Example The following script component fragment defines a resource (called errNonNumeric) and demonstrates how to use it in script. Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance. Non-numeric value passed
See Also Referencing Other Components
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Element
1
2
Element
Windows Script Components
2
Element
Element Defines the script component's behavior. script here
Values language The name of the scripting language used in the script component file, such as Microsoft® Visual Basic® Scripting Edition (VBScript) or JScript. Remarks If XML validation is not enabled, the XML parser ignores all lines inside the element. However, if XML validation is enabled by including the declaration at the top of the script component file, the XML parser can misinterpret greater than (), and other symbols used in script as XML delimiters. If you are creating a file that conforms closely to XML syntax, you must make sure that characters in your script element are not treated as XML reserved characters. To do so, enclose the actual script in a section. For details about XML validation, see Script Component Files and XML Conformance. Note Do not include a CDATA section unless you also include the declaration. Example Element
Element Binds an event from the containing document to a function in the script component.
Values eventName The event being bound, such as onmouseclick. functionName The name of the procedure (function or subroutine) in the script component file that is executed in response to the event. If this attribute is omitted, it is generated. If the for attribute is not specified, the default value of the handler attribute is the value of the event attribute. If the for attribute is specified, the default handler attribute value is the string generated by concatenating the for attribute value, "_", and the event attribute value. elementName The element associated with the event, used for containing elements to which DHTML Behaviors are not explicitly attached. The only possible values for the for attribute are "document," "window," and "element." If the for attribute is not included, "element" is the default and the event is assumed to be fired on the element to which the behavior is attached. Example In the following example, the element binds three events to functions. For example, the DHTML onmouseover element is bound to the script component's do_onmouseover function. The functions bound to the DHTML onmouseover and onmouseout events are executed only if they are fired on the element in the containing document to which the behavior is attached. The docinit function is explicitly bound to the DHTML document object's onload event. Note A CDATA section is required to make the script in the element opaque. For details, see Script Component Files and XML Conformance. Element
1
2
Element
} ]]>
See Also Creating a Behavior Script Component
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Windows Script Components
2
Element
element Property Returns the element to which the behavior is being applied. [oElement = ] Behavior.element
Values oElement Element to which the behavior is being applied. Behavior The ID of the element used to implement the Behavior interface. Note By default, the properties and methods exposed by the Behavior handler are automatically added to the global script namespace and can be accessed without referencing the Behavior handler ID. In this case, instead of using Behavior.element as shown in the syntax, the property can be used in script simply as element. For more details, see the 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 a script component. The script component attaches to the element's DHTML onmouseover event. It sets the DHTML cursor property of the element to "hand" to signal the user that the element can be clicked in order to toggle visibility of its children. Note A CDATA section is required to make the script in the element opaque. For details, seeScript Component Files and XML Conformance.
See Also For general information about applying behaviors to DHTML elements, see the "Using DHTML Behaviors" topic on the Site Builder Network (SBN)
element Property
1
2
element Property
© 2001 Microsoft Corporation. All rights reserved. Build: Topic Version 5.6.9309.1546 Windows Script Components
2
element Property
Element Defines HTML text inserted into the containing document. Inserted text
Values HTMLTag The name of HTML tag for which the element's text is a replacement. Remarks When the behavior is called, the text in the element is read into the corresponding element in the containing document. This behavior is equivalent to setting the element's DHTML innerHTML property. If the script component is not defined to be XML-conformant, the contents of the element are opaque. However, if the script component is XML-conformant, the contents of the element must explicitly be made opaque by including them in a CDATA. For more details, see Script Component Files and XML Conformance. Example The following shows an example of a script component with a element. Because the script component contains the declaration at the top, the element contains a CDATA section to make the contents of the element opaque to the XML parser. This is the HTML to show in the element ]]>
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 Script Interfaces-Introduction Element
Language Reference Next
1
2
Element Microsoft® Windows® Script Interfaces introduce a new way for an application to add scripting and OLE Automation capabilities. With the advent of the interfaces, hosts can call upon disparate scripting engines from multiple sources and vendors to perform scripting between components. The implementation of the script itselflanguage, syntax, persistent format, execution model, and so onis left to the script vendor. The designers have taken care to allow hosts that rely on Windows Script to use arbitrary language back ends. ♦ 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
Code object
An instance created by the scripting engine that is associated with a named 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 Component Object Model (COM) object that supports OLE Automation so the host or other nonscript entity can manipulate the code object.
Named item
An OLE COM object (preferably one that supports OLE Automation) that the host deems interesting to the script. Examples include the HTML Page and Browser in a Web browser, and the Document and Dialogs in Microsoft Word.
Script
The data that makes up the program that the scripting engine runs. A script can be any contiguous executable data, including pieces of text, blocks of pcode, or even machine-specific executable byte codes. A host loads a script into the scripting engine through one of the IPersist* interfaces or through the IActiveScriptParse interface.
Scripting engine
The OLE object that processes scripts. A scripting engine implements the IActiveScript and, optionally, IActiveScriptParse interfaces.
Scripting host
The application or program that owns the Windows Script engine. The host implements the IActiveScriptSite and, optionally, IActiveScriptSiteWindow interfaces.
Scriptlet
A portion of a script that gets attached to an object through the IActiveScriptParse interface. The aggregate collection of scriptlets is the script.
Script language
The language in which a script is written (VBScript, for example) and the semantics of that language.
Windows Script Background
Windows Script components fall into two categories: Windows Script hosts and Windows Script engines. A host creates a scripting engine and calls on the engine to run the scripts. Examples of Windows Script hosts include: ♦ 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
Element
Element
3
♦ Lisp
To make implementation of the host as flexible as possible, an OLE Automation wrapper for Windows Script is provided. However, a host that uses this wrapper object to instantiate the scripting engine does not have the degree of control over the run-time name space, the persistence model, and so on, that it would if it used Windows Script directly. The Windows Script design isolates the interface elements required only in an authoring environment so that nonauthoring hosts (such as browsers and viewers) and script engines (for example, VBScript) can be kept lightweight. Windows Script Basic Architecture
The following illustration shows the interaction between an Windows Script host and an Windows Script engine.
Following is a description of the steps involved in the interaction between the host and engine. The actual nesting of the function calls is omitted for clarity. 1. Create a Project. The host loads a project or document. (This step is not particular to Windows Script, but is included here for completeness.) 2. Create the Windows Script Engine. The host calls CoCreateInstance to create a new Windows Script engine, specifying the class identifier (CLSID) of the specific scripting engine to use. For example, the HTML browsing component of Internet Explorer receives the scripting engine's class identifier through the CLSID= attribute of the HTML tag. 3. Load the Script. If the script contents have been persisted, the host calls the script engine's IPersist*::Load method to feed it the script storage, stream, or property bag. Otherwise, the host uses either the IPersist*::InitNew or IActiveScriptParse::InitNew method to create a null script. A host that maintains a script as text can use IActiveScriptParse::ParseScriptText to feed the scripting engine the text of the script, after calling IActiveScriptParse::InitNew. 4. Add Named Items. For each top-level named item (such as pages and forms) imported into the scripting engine's name space, the host calls the IActiveScript::AddNamedItem method to create an entry in the engine's name space. This step is not necessary if top-level named items are already part of the persistent state of the script loaded in step 3. A host does not use IActiveScript::AddNamedItem to add sublevel named items (such as controls on an HTML page); rather, the engine indirectly obtains sublevel items from top-level items by using the host's ITypeInfo and IDispatch interfaces. 5. Run the Script. The host causes the engine to start running the script by setting the SCRIPTSTATE_CONNECTED flag in the IActiveScript::SetScriptState method. This call would likely perform any scripting engine construction work, including static binding, hooking up to events (see below), and executing code, in a way similar to a scripted main() function. 6. Get Item Information. Each time the script engine needs to associate a symbol with a top-level item, it calls the IActiveScriptSite::GetItemInfo method, which returns information
Element
3
4
Element about the given item. 7. Hook Up Event Advise. Before starting the actual script, the scripting engine connects to the events of all the relevant objects through the IConnectionPoint interface. 8. Invoke Properties and Methods. As the script runs, the scripting engine realizes references to methods and properties on named objects through IDispatch::Invoke or other standard OLE binding mechanisms.
Microsoft® Windows® Script Interfaces
Windows Script Hosts
Language Reference Previous Next
When implementing Microsoft® Windows® Script host, you can safely assume that a scripting engine will only call the IActiveScriptSite interface in the context of the base thread as long as the host does the following: ♦ Chooses a base thread (generally the thread that contains the message loop). ♦ Instantiates the scripting engine in the base thread. ♦ Calls scripting engine methods only from the base thread, except where specifically allowed, as in the cases of IActiveScript::InterruptScriptThread and IActiveScript::Clone. ♦ Calls the scripting engine's dispatch object only from the base thread. ♦ Ensures that the message loop runs in the base thread if a window handle is provided. ♦ Ensures that objects in the host's object model only source events in the base thread.
These rules are automatically followed by all single-threaded hosts. The restricted model described above is intentionally loose enough to allow a host to abort a stuck script by calling IActiveScript::InterruptScriptThread from another thread (initiated by a CTRL+BREAK handler or the like), or to duplicate a script in a new thread using IActiveScript::Clone. Also, none of these restrictions apply to a host that chooses to implement a free-threaded IActiveScriptSite interface and a free-threaded object model. Such a host can use the IActiveScript interface from any thread, without restriction. Microsoft® Windows® Script Interfaces
Windows Script Engines
Language Reference Previous Next
To implement an Microsoft® Windows® Script engine, create an OLE COM object that supports the following interfaces. Interface
Description
IActiveScript
Provides the basic scripting ability. Implementation of this interface is required.
IActiveScriptParse
Provides the ability to add script text, evaluate expressions, and so on. Implementation of this interface is optional; however, if it is not implemented, the script engine must implement one of the IPersist* interfaces in order to load a script.
IPersist*
Provides persistence support. Implementation of at least one of the following interfaces is required if IActiveScriptParse is not implemented. Interface Description IPersistStorage
Provides support for the DATA={url} attribute in the OBJECT tag.
IPersistStreamInit
Provides support for the same as IPersistStorage as well as the DATA="string-encoded byte stream" attribute in the OBJECT tag.
IPersistPropertyBag Provides support for the PARAM= attribute in the OBJECT tag.
4
Element
Element
5
Note: It is possible that the scripting engine will never be called upon to save or restore a script state through IPersist*. Instead, IActiveScriptParse is used by calling IActiveScriptParse::InitNew to create a blank script, then scriptlets are added and connected to events with IActiveScriptParse::AddScriptlet and general code is added with IActiveScriptParse::ParseScriptText. Nonetheless, a scripting engine should fully implement at least one IPersist* interface (preferably IPersistStreamInit), because other host applications may try to make use of them. The following sections describe implementing a Windows Scripting engine in more detail. ♦ Registry Standard ♦ Script Engine States ♦ Scripting Engine Threading
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, at a minimum, the IActiveScript interface and a persistence mechanism (the IPersistStorage, IPersistStreamInit, or IPersistPropertyBag interface).
CATID_ActiveScriptParse
Indicates that the CLSIDs are Windows Script engines that support, at a minimum, the IActiveScript and IActiveScriptParse interfaces.
Although IActiveScriptParse is not a true persistence mechanism, it does support the IActiveScriptParse::InitNew method that is functionally equivalent 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 an IPersist* interface, or does not have an IActiveScriptSite interface set. The scripting engine is generally not usable from this state until the script is loaded.
initialized
The script has been initialized with an IPersist* interface and has an IActiveScriptSite interface set, but is not connected to host objects and sinking events. Note that this state simply means that the IPersist*::Load, IPersist*::InitNew, or IActiveScriptParse::InitNew method has been completed, and that the IActiveScript::SetScriptSite method has been called. The engine cannot run code in this mode. The engine queues code that the host passes to it through the IActiveScriptParse::ParseScriptText method, and executes the code after transitioning to the started state.
Element
5
6
Element Because languages can vary widely in semantics, scripting engines are not required to support this state transition. Engines that support the IActiveScript::Clone method must, however, support this state transition. Hosts must prepare for this transition and take the appropriate action: release the current scripting engine, create a new scripting engine, and call IPersist*::Load, IPersist*::InitNew, or IActiveScriptParse::InitNew (and possibly also call IActiveScriptParse::ParseScriptText). Use of this transition should be considered an optimization of the above steps. Note that any information the scripting engine has obtained about the names of Named Items and the type information describing Named Items remains valid. Because languages vary widely, defining the exact semantics of this transition is difficult. At a minimum, the scripting engine must disconnect from all events, and release all of the SCRIPTINFO_IUNKNOWN pointers obtained by calling the IActiveScriptSite::GetItemInfo method. The engine must re-obtain these pointers after the script is run again. The scripting engine should also reset the script back to an initial state that is appropriate for the language. VBScript, for example, resets all variables and retains any code added dynamically by calling IActiveScriptParse::ParseScriptText with the SCRIPTTEXT_ISPERSISTENT flag set. Other languages may need to retain current values (such as Lisp because there is no code/data separation) or reset to a well-known state (this includes languages with statically initialized variables). Note that the transition to the started state should have the same semantics (that is, it should leave the scripting engine in the same state) as calling IPersist*::Save to save the scripting engine, and then calling IPersist*::Load to load a new scripting engine; these actions should have the same semantics as IActiveScript::Clone. Scripting engines that do not yet support IActiveScript::Clone or IPersist* should carefully consider how the transition to the started state should behave, so that such a transition would not violate the above conditions if IActiveScript::Clone or IPersist* support was later added. During this transition to the started state, the scripting engine will disconnect from event sinks after the appropriate destructors, and so on, are
6
Element
Element
7 executed in the script. To avoid having these destructors executed, the host can first move the script into the disconnected state before moving into the started state. Use IActiveScript::InterruptScriptThread to cancel a running script thread without waiting for current events, and so on, to finish running.
started
The transition from the initialized state to the started state causes the engine to execute any code that was queued in the initialized state. The engine can execute code while in the started state, but it is not connected to any events added through the IActiveScript::AddNamedItem method. The engine can execute code by calling the IDispatch interface obtained from the IActiveScript::GetScriptDispatch method, or by calling IActiveScriptParse::ParseScriptText. It is possible that further background initialization (progressive loading) is still ongoing, and that calling the IActiveScript::SetScriptState method with the SCRIPTSTATE_CONNECTED flag set may cause the script to block until initialization is complete.
connected
The script is loaded and connected for sinking events from host objects. If this is a transition from the initialized state, the scripting engine should transition through the started state, performing the necessary actions, before entering the connected state and connecting to events.
disconnected
The script is loaded and has a run-time state, but is temporarily disconnected from sinking events from host objects. This can be done either logically (ignoring events received) or physically (calling IConnectionPoint::Unadvise on the appropriate connection points). If this is a transition from the initialized state, the scripting engine should transition through the started state, performing the necessary actions, before entering the disconnected state. Event sinks that are in progress are completed before the state changes (use IActiveScript::InterruptScriptThread to cancel a running script thread). This state is distinguished from the initialized state in that the transition to this state does not cause the script to reset, the run-time state of the script is not reset, and a script initialization procedure is not executed.
closed
The script has been closed. The scripting engine no longer works and returns errors for most methods.
The following illustration shows the relationships between the various scripting engine states, and shows the methods that cause transitions from one state to another.
Element
7
8
Element
The following illustration shows the actions that the scripting engine performs during the various state transitions.
Scripting Engine Threading
Because an Windows Script engine can be used in many environments, it is important to keep its execution model as flexible as possible. For example, a server-based host may need to preserve a multithreaded design while using Windows Script in an efficient manner. At the same time, a host that does not use threading, such as a typical application, should not be burdened with threading management. Windows Script achieves this balance by restricting the ways a free-threaded scripting engine can call back to the host, freeing hosts from this burden. Scripting engines used on servers are typically implemented as free-threading COM objects. This means that methods on the IActiveScript interface and its associated interfaces can be called from any thread in the process, without 8
Element
Element
9
marshaling. (Unfortunately, this also means that the scripting engine must be implemented as an in-process server, because OLE does not currently support interprocess marshaling of free-threaded objects.) Synchronization is the responsibility of the scripting engine. For scripting engines that are not internally reentrant, or for language models that are not multithreaded, synchronization could be as simple as serializing access to the scripting engine with a mutex. Of course certain methods, such as IActiveScript::InterruptScriptThread, should not be serialized in this way so that a stuck script can be terminated from another thread. The fact that IActiveScript is typically free-threaded generally implies that the IActiveScriptSite interface and the host's object model should be free-threaded as well. This would make implementation of the host quite difficult, particularly in the common case where the host is a single-threaded Microsoft Windows®-based application with single-threaded or apartment-model ActiveX Controls in its object model. For this reason, the following constraints are placed on the scripting engine's use of IActiveScriptSite: ◊ The script site is always called in the context of a host thread. That is, the scripting engine never calls the script site in the context of a thread that the scripting engine created, but only from within a scripting engine method that was called from the host through IActiveScript and its derivatives, through the exposed scripting engine's dispatch object, through a Windows message, or from an event source in the host's object model. ◊ The script site is never called from within the context of a simple thread state control method (for example, the IActiveScript::InterruptScriptThread method) or from the IActiveScript::Clone method.
Microsoft® Windows® Script Interfaces
Windows Script Interface Reference
Language Reference Previous Next
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 Language Reference Previous Next
Microsoft® Windows® Script Interfaces
IActiveScript
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
Element
Description
9
10
Element SetScriptSite
Informs the scripting engine of the IActiveScriptSite site provided by the host.
GetScriptSite
Retrieves the site object associated with the Windows Script 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 currently loaded script, lose its state, and release any interface pointers it has to other objects, thus entering a closed state.
AddNamedItem
Adds the name of a root-level item to the scripting engine's name 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 the currently executing thread.
GetScriptThreadID
Retrieves a scripting-engine-defined identifier for the thread associated 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 current execution state), returning a loaded scripting engine that has no site in the current thread. Language Reference Previous Next
Microsoft® Windows® Script Interfaces
IActiveScript::AddNamedItem HRESULT AddNamedItem( LPCOLESTR pstrName, DWORD dwFlags );
// address of item name // item flags
Adds the name of a root-level item to the scripting engine's name space. A root-level item is an object with properties and methods, an event source, or all three. • 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 loaded or initialized).
pstrName [in] Address of a buffer that contains the name of the item as viewed from the script. The name must be unique and persistable. dwFlags [in] Flags associated with an item. Can be a combination of these values: 10
Element
Element
11
Value
Meaning
SCRIPTITEM_CODEONLY
Indicates that the named item represents a code-only object, and that the host has no IUnknown to be associated with this code-only object. The host only has a name for this object. In object-oriented languages such as C++, this flag would create a class. Not all languages support this flag.
SCRIPTITEM_GLOBALMEMBERS
Indicates that the item is a collection of global properties and methods associated with the script. Normally, a scripting engine would ignore the object name (other than for the purpose of using it as a cookie for the IActiveScriptSite::GetItemInfo method, or for resolving explicit scoping) and expose its members as global variables and methods. This allows the host to extend the library (run-time functions and so on) available to the script. It is left to the scripting engine to deal with name conflicts (for example, when two SCRIPTITEM_GLOBALMEMBERS items have methods of the same name), although an error should not be returned because of this situation.
SCRIPTITEM_ISPERSISTENT
Indicates that the item should be saved if the scripting engine is saved. Similarly, setting this flag indicates that a transition back to the initialized state should retain the item's name and type information (the scripting engine must, however, release all pointers to interfaces on the actual object).
SCRIPTITEM_ISSOURCE
Indicates that the item sources events that the script can sink. Child objects (properties of the object that are in themselves objects) can also source events to the script. This is not recursive, but it provides a convenient mechanism for the common case, for example, of creating a container and all of its member controls.
SCRIPTITEM_ISVISIBLE
Indicates that the item's name is available in the name space of the script, allowing access to the properties, methods, and events of the item. By convention the properties of the item include the item's children; therefore, all child object properties and methods (and their children, recursively) will be accessible.
SCRIPTITEM_NOCODE
Indicates that the item is simply a name being added to the script's name space, and should not be treated as an item for which code should be associated. For example, without this flag being set, VBScript will create a separate module for the named item, and C++ might create a separate wrapper class for the named item. Language Reference Previous Next
Microsoft® Windows® Script Interfaces
IActiveScript::AddTypeLib HRESULT AddTypeLib( REFGUID guidTypeLib, DWORD dwMaj, DWORD dwMin, DWORD dwFlags );
// // // //
CLSID of type library major version number minor version number option flags
Adds a type library to the name space for the script. This is similar to the #include directive in C/C++. It allows a set of predefined items such as class definitions, typedefs, and named constants to be added to the run-time environment available to the script. • Returns one of the following values: Return Value
Element
Meaning
11
12
Element S_OK
Success.
E_INVALIDARG
An argument was invalid.
E_UNEXPECTED
The call was not expected (for example, the scripting engine has not yet 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. Language Reference Previous Next
Microsoft® Windows® Script Interfaces
IActiveScript::Clone HRESULT Clone( IActiveScript **ppscript );
// receives pointer to IActiveScript
Clones the current scripting engine (minus any current execution state), returning a loaded scripting engine that has no site in the current thread. The properties of this new scripting engine will be identical to the properties the original scripting engine would be in if it were transitioned back to the initialized state. • 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 loaded or initialized).
ppscript [out] Address of a variable that receives a pointer to the IActiveScript interface of the cloned scripting engine. The host must create a site and call the IActiveScript::SetScriptSite method on the new scripting engine before it will be in the initialized state and, therefore, usable. The IActiveScript::Clone method is an optimization of IPersist*::Save, CoCreateInstance, and IPersist*::Load, so the state of the new scripting engine should be the same as if the state of the original scripting engine were saved and loaded into a new scripting engine. Named items are duplicated in the cloned scripting engine, but specific object pointers for each item are forgotten and are obtained with the IActiveScriptSite::GetItemInfo method. This allows an identical object model with per-thread entry points (an apartment model) to be used. 12
Element
Element
13
This method is used for multithreaded server hosts that can run multiple instances of the same script. The scripting engine may return E_NOTIMPL, in which case the host can achieve the same result by duplicating the persistent state and creating a new instance of the scripting engine with an IPersist* interface. This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface. Language Reference Previous Next
Microsoft® Windows® Script Interfaces
IActiveScript::Close HRESULT Close(void);
Causes the scripting engine to abandon any currently loaded script, lose its state, and release any interface pointers it has to other objects, thus entering a closed state. Event sinks, immediately executed script text, and macro invocations that are already in progress are completed before the state changes (use IActiveScript::InterruptScriptThread to cancel a running script thread). This method must be called by the creating host before the interface is released to prevent circular reference problems. • 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 in the closed state).
OLESCRIPT_S_PENDING
The method was queued successfully, but the state hasn't changed yet. When the state changes, the site will be called back on the IActiveScriptSite::OnStateChange method.
S_FALSE
The method succeeded, but the script was already closed.
Microsoft® Windows® Script Interfaces
IActiveScript::GetCurrentScriptThreadID
Language Reference Previous Next
HRESULT GetCurrentScriptThreadID( SCRIPTTHREADID *pstidThread // receives scripting thread identifier ); Retrieves a scripting-engine-defined identifier for the currently executing thread. The identifier can be used in subsequent calls to script thread execution-control methods such as the IActiveScript::InterruptScriptThread method. • 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 the Windows thread identifier. If the Win32 thread terminates, this identifier becomes unassigned and can subsequently be assigned to another thread. This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface. Microsoft® Windows® Script Interfaces
Element
Language Reference Previous
13
14
Element Next
IActiveScript::GetScriptDispatch HRESULT GetScriptDispatch( LPCOLESTR pstrItemName IDispatch **ppdisp );
// address of item name // 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 loaded or initialized).
S_FALSE
The scripting engine does not support a dispatch object; the ppdisp parameter is set to NULL.
pstrItemName [in] Address of a buffer that contains the name of the item for which the caller needs the associated dispatch object. If this parameter is NULL, the dispatch object contains as its members all of the global methods and properties defined by the script. Through the IDispatch interface and the associated ITypeInfo interface, the host can invoke script methods or view and modify script variables. ppdisp [out] Address of a variable that receives a pointer to the object associated with the script's global methods and properties. If the scripting engine does not support such an object, NULL is returned. Because methods and properties can be added by calling the IActiveScriptParse interface, the IDispatch interface returned by this method can dynamically support new methods and properties. Similarly, the IDispatch::GetTypeInfo method should return a new, unique ITypeInfo interface when methods and properties are added. Note, however, that language engines must not change the IDispatch interface in a way that is incompatible with any previous ITypeInfo interface returned. That implies, for example, that DISPIDs will never be reused. Language Reference Previous Next
Microsoft® Windows® Script Interfaces
IActiveScript::GetScriptSite HRESULT GetScriptSite( REFIID iid, void **ppvSiteObject );
// interface identifier // address of host site interface
Retrieves the site object associated with the Windows Script engine. • Returns one of the following values:
14
Return Value
Meaning
S_OK
Success.
Element
Element
15
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::GetScriptState
Language Reference Previous Next
HRESULT GetScriptState( SCRIPTSTATE *pss // address of structure for state information ); Retrieves the current state of the scripting engine. This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface. • 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. The value indicates the current state of the scripting engine associated with the calling thread. Microsoft® Windows® Script Interfaces
IActiveScript::GetScriptThreadID HRESULT GetScriptThreadID( DWORD dwWin32ThreadID, SCRIPTTHREADID *pstidThread );
Language Reference Previous Next
// Win32 thread identifier // 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 loaded or initialized) and therefore failed.
dwWin32ThreadID [in] Thread identifier of a running Win32 thread in the current process. Use the GetCurrentScriptThreadID function to retrieve the thread identifier of the currently executing thread. pstidThread [out] Address of a variable that receives the script thread identifier associated with the given Win32 thread. The interpretation of this identifier is left to the scripting engine, but it can be just a copy of the Windows thread identifier. Note that if the Win32 thread terminates, this identifier becomes Element
15
16
Element 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 the IActiveScript::InterruptScriptThread method. This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface. Language Reference Previous Next
Microsoft® Windows® Script Interfaces
IActiveScript::GetScriptThreadState HRESULT GetScriptThreadState( SCRIPTTHREADID stidThread, SCRIPTTHREADSTATE *pstsState );
// identifier of script thread // 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 loaded or initialized).
stidThread [in] Identifier of the thread for which the state is desired, or one of the following special thread identifiers: Value
Meaning
SCRIPTTHREADID_BASE
The base thread; that is, the thread in which the scripting engine was instantiated.
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 one of the named constant values defined by the SCRIPTTHREADSTATE enumeration. If this parameter does 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 to the IActiveScriptSite interface. Microsoft® Windows® Script Interfaces
IActiveScript::InterruptScriptThread HRESULT InterruptScriptThread( SCRIPTTHREADID stidThread, const EXCEPINFO *pexcepinfo, DWORD dwFlags );
16
Language Reference Previous Next
// identifier of thread // receives error information
Element
Element
17
Interrupts the execution of a running script thread (an event sink, an immediate execution, or a macro invocation). This method can be used to terminate a script that is stuck (in an infinite loop, for example). It can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite method. • 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 loaded or 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 script methods currently in progress. Note that unless the caller has requested that the script be disconnected, by calling the IActiveScript::SetScriptState method with the SCRIPTSTATE_DISCONNECTED or SCRIPTSTATE_INITIALIZED flag set, the next scripted event causes script code to run again.
SCRIPTTHREADID_BASE
The base thread; that is, the thread in which the scripting engine was instantiated.
SCRIPTTHREADID_CURRENT
The currently executing thread.
pexcepinfo [in] Address of an EXCEPINFO structure that receives error information associated with the error condition. 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 the current script execution point.
SCRIPTINTERRUPT_RAISEEXCEPTION
If supported by the scripting engine's language, let the script handle the exception. Otherwise, the script method is aborted and the error code is returned to the caller; that is, the event source or macro invoker.
Microsoft® Windows® Script Interfaces
IActiveScript::SetScriptSite HRESULT SetScriptSite( IActiveScriptSite *pScriptSite );
Language Reference Previous Next
// address of host script site
Informs the scripting engine of the IActiveScriptSite interface site provided by the host. This method must be called before any other IActiveScript interface methods can be used. Element
17
18
Element • 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 initializing the 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 other scripting engines. Microsoft® Windows® Script Interfaces
IActiveScript::SetScriptState
Language Reference Previous Next
HRESULT SetScriptState( SCRIPTSTATE ss // identifier of new state ); Puts the scripting engine into the given state. This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface. • 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 initialized state. The host must discard this scripting engine and create, initialize, and load a new scripting engine to achieve the same effect.
E_UNEXPECTED
The call was not expected (for example, the scripting engine has not yet been loaded or initialized) and therefore failed.
OLESCRIPT_S_PENDING
The method was queued successfully, but the state has not changed yet. When the state changes, the site will be called back through the IActiveScriptSite::OnStateChange method.
S_FALSE
The method succeeded, but the script was already in the given state.
ss [in] Sets the scripting engine to the given state. Can be one of the values defined in the SCRIPTSTATE enumeration. For more information about scripting engine states, see Script Engine States. See also IActiveScript::Clone, IActiveScript::GetScriptDispatch, IActiveScript::InterruptScriptThread, IActiveScriptParse::ParseScriptText, IActiveScriptSite::GetItemInfo Microsoft® Windows® Script Interfaces
IActiveScriptError 18
Language Reference Previous Next
Element
Element
19
An object implementing this interface is passed to the IActiveScriptSite::OnScriptError method whenever the scripting engine encounters an unhandled error. The host then calls methods 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::GetExceptionInfo HRESULT GetExceptionInfo( EXCEPINFO *pexcepinfo );
Language Reference Previous Next
// 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::GetSourceLineText
Language Reference Previous Next
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::GetSourcePosition HRESULT GetSourcePosition( DWORD *pdwSourceContext, ULONG *pulLineNumber, LONG *pichCharPosition );
Language Reference Previous Next
// context cookie // line number of error // character position of error
Retrieves the location in the source code where an error occurred while the scripting engine was running a script.
Element
19
20
Element • 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 this parameter depends on the host application. pulLineNumber [out] Address of a variable that receives the line number in the source file where the error occurred. pichCharPosition [out] Address of a variable that receives the character position in the line where the error occurred. Language Reference Previous Next
Microsoft® Windows® Script Interfaces
IActiveScriptParse
If the Windows Script engine allows raw text code scriptlets to be added to the script or allows expression text to be evaluated at run time, it implements the IActiveScriptParse interface. For interpreted scripting languages that have no independent authoring environment, such as VBScript, this provides an alternate mechanism (other than IPersist*) to get script code into the scripting engine, and to attach script fragments to various object events. 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 name space and evaluating code as appropriate. Language Reference Previous Next
Microsoft® Windows® Script Interfaces
IActiveScriptParse::AddScriptlet HRESULT AddScriptlet( LPCOLESTR pstrDefaultName, LPCOLESTR pstrCode, LPCOLESTR pstrItemName, LPCOLESTR pstrSubItemName, LPCOLESTR pstrEventName, LPCOLESTR pstrDelimiter, DWORD dwSourceContextCookie, ULONG ulStartingLineNumber, DWORD dwFlags, BSTR *pbstrName, EXCEPINFO *pexcepinfo );
// // // // // // // // // // //
address of default name of scriptlet address of scriptlet text address of item name address of subitem name address of event name address of end-of-scriptlet delimiter application-defined value for debugging starting line of the script scriptlet flags address of actual name of scriptlet address of exception information
Adds a code scriptlet to the script. This method is used in environments where the persistent state of the script is intertwined with the host document and the host is responsible for restoring the script, rather than through an IPersist* interface. The primary examples are HTML scripting languages that allow scriptlets of code embedded in the HTML document to be attached to intrinsic events (for instance, ONCLICK="button1.text='Exit'"). • Returns one of the following values:
20
Element
Element
21
Return Value
Meaning
S_OK
Success.
DISP_E_EXCEPTION
An exception occurred in the parsing of the scriptlet; the pexcepinfo parameter contains information about the exception.
E_INVALIDARG
An argument was invalid.
E_NOTIMPL
This method is not supported; the scripting engine does not support adding event-sinking scriptlets.
E_POINTER
An invalid pointer was specified.
E_UNEXPECTED
The call was not expected (for example, the scripting engine has not yet 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 naming information (as in the ONCLICK example above), this name will be used to identify the scriptlet. If this parameter is NULL, the scripting engine manufactures a unique name, if necessary. pstrCode [in] Address of the scriptlet text to add. The interpretation of this string depends on the scripting language. pstrItemName [in] Address of a buffer that contains the item name associated with this scriptlet. This parameter, in addition to pstrSubItemName, identifies the object for which the scriptlet is an event handler. pstrSubItemName [in] Address of a buffer that contains the name of a subobject of the named item with which this scriptlet is associated; this name must be found in the named item's type information. This parameter is NULL if the scriptlet is to be associated with the named item instead of a subitem. This parameter, in addition to pstrItemName, identifies the specific object for which the scriptlet is an event handler. pstrEventName [in] Address of a buffer that contains the name of the event for which the scriptlet is an event handler. pstrDelimiter [in] Address of the end-of-scriptlet delimiter. When the pstrCode parameter is parsed from a stream of text, the host typically uses a delimiter, such as two single quotation marks ("), to detect the end of the scriptlet. This parameter specifies the delimiter that the host used, allowing the scripting engine to provide some conditional primitive preprocessing (for example, replacing a single quotation mark ['] with two single quotation marks for use as a delimiter). Exactly how (and if) the scripting engine makes use of this information depends on the scripting engine. Set this parameter to NULL if the host did not use a delimiter to mark the end of the scriptlet. dwSourceContextCookie [in] Application-defined value that is used for debugging purposes. ulStartingLineNumber [in] Zero-based value that specifies which line the parsing will begin at. dwFlags [in] Flags associated with the scriptlet. Can be a combination of the following values: 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 the script.
SCRIPTTEXT_ISPERSISTENT
Element
21
22
Element Indicates that the code added during this call should be saved if the scripting engine is saved (for example, through a call to IPersist*::Save), or if the scripting engine is reset by way of a transition back to the initialized state. For more information about this state, see Script Engine States.
pbstrName [out] Actual name used to identify the scriptlet. This will be, in order of preference: a name explicitly specified in the scriptlet text, the default name provided in pstrDefaultName, or a unique name synthesized by the scripting engine. pexcepinfo [out] Address of a structure containing exception information. This structure should be filled in if DISP_E_EXCEPTION is returned. Language Reference Previous Next
Microsoft® Windows® Script Interfaces
IActiveScriptParse::InitNew 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 to IPersistStreamInit::InitNew, in that this method tells the scripting engine to initialize itself. Note that it is not valid to call both IPersist*::InitNew or IActiveScriptParse::InitNew and IPersist*::Load, nor is it valid to call IPersist*::InitNew, IActiveScriptParse::InitNew, or IPersist*::Load more than once. Language Reference Previous Next
Microsoft® Windows® Script Interfaces
IActiveScriptParse::ParseScriptText HRESULT ParseScriptText( LPCOLESTR pstrCode, LPCOLESTR pstrItemName, IUnknown *punkContext, LPCOLESTR pstrDelimiter, DWORD dwSourceContextCookie, ULONG ulStartingLineNumber, DWORD dwFlags, VARIANT *pvarResult, EXCEPINFO *pexcepinfo );
// // // // // // // // //
address of scriptlet text address of item name address of debugging context address of end-of-scriptlet delimiter application-defined value for debugging starting line of the script scriptlet flags address of buffer for results 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:
22
Return Value
Meaning
S_OK
Success.
DISP_E_EXCEPTION
An exception occurred in the processing of the scriptlet. The pexcepinfo parameter contains information about the exception.
E_INVALIDARG
An argument was invalid.
Element
Element
23
E_POINTER
An invalid pointer was specified.
E_NOTIMPL
This method is not supported. The scripting engine does not support run-time evaluation of expressions or statements.
E_UNEXPECTED
The call was not expected (for example, the scripting engine is in the uninitialized or closed state, or the SCRIPTTEXT_ISEXPRESSION flag was set and the scripting engine is in the initialized state).
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 scripting language. pstrItemName [in] Address of the item name that gives the context in which the scriptlet is to be evaluated. If this parameter is NULL, the code is evaluated in the scripting engine's global context. punkContext [in] Address of the context object. This object is reserved for use in a debugging environment, where such a context may be provided by the debugger to represent an active run-time context. If this parameter is NULL, the engine uses pstrItemName to identify the context. pstrDelimiter [in] Address of the end-of-scriptlet delimiter. When pstrCode is parsed from a stream of text, the host typically uses a delimiter, such as two single quotation marks ("), to detect the end of the scriptlet. This parameter specifies the delimiter that the host used, allowing the scripting engine to provide some conditional primitive preprocessing (for example, replacing a single quotation mark ['] with two single quotation marks for use as a delimiter). Exactly how (and if) the scripting engine makes use of this information depends on the scripting engine. Set this parameter to NULL if the host did not use a delimiter to mark the end of the scriptlet. dwSourceContextCookie [in] Application-defined value that is used for debugging purposes. ulStartingLineNumber [in] Zero-based value that specifies which line the parsing will begin at. dwFlags [in] Flags associated with the scriptlet. Can be a combination of these values: Value
Meaning
SCRIPTTEXT_ISEXPRESSION
If the distinction between a computational expression and a statement is important but syntactically ambiguous in the script language, this flag specifies that the scriptlet is to be interpreted as an expression, rather than as a statement or list of statements. By default, statements are assumed unless the correct choice can be determined from the syntax of the scriptlet text.
SCRIPTTEXT_ISPERSISTENT
Indicates that the code added during this call should be saved if the scripting engine is saved (for example, through a call to IPersist*::Save), or if the scripting engine is reset by way of a transition back to the initialized state.
SCRIPTTEXT_ISVISIBLE
Indicates that the script text should be visible (and, therefore, callable by name) as a global method in the name space of the script.
pvarResult [out] Address of a buffer that receives the results of scriptlet processing, or NULL if the caller expects no result (that is, the SCRIPTTEXT_ISEXPRESSION value is not set). pexcepinfo [out] Address of a structure that receives exception information. This structure is filled if IActiveScriptParse::ParseScriptText returns DISP_E_EXCEPTION.
Element
23
24
Element
If the scripting engine is in the initialized state, no code will actually be evaluated during this call; rather, such code is queued and executed when the scripting engine is transitioned into (or through) the started state. Because execution is not allowed in the initialized state, it is an error to call this method with the SCRIPTTEXT_ISEXPRESSION flag when in the initialized state. The scriptlet can be an expression, a list of statements, or anything allowed by the script language. For example, this method is used in the evaluation of the HTML tag, which allows statements to be executed as the HTML page is being constructed, rather than just compiling them into the script state. The code passed to this method must be a valid, complete portion of code. For example, in VBScript it is illegal to call this method once with Sub Function(x) and then a second time with End Sub. The parser must not wait for the second call to complete the subroutine, but rather must generate a parse error because a subroutine declaration was started but not completed. For more information about script states, see Script Engine States. Language Reference Previous Next
Microsoft® Windows® Script Interfaces
IActiveScriptSite
The host must create a site for the Windows Script engine by implementing the IActiveScriptSite interface. Usually, this site will be associated with the container of all the objects that are visible to the script (for example, the ActiveX Controls). Typically, this container will correspond to the document or page being viewed. Microsoft Internet Explorer, for example, would create such a container for each HTML page being displayed. Each ActiveX control (or other automation object) on the page, and the scripting engine itself, would be enumerable within this container. Methods in Vtable Order Method
Description
GetLCID
Retrieves the locale identifier that the host uses for displaying user-interface elements.
GetItemInfo
Obtains information about an item that was added to an engine through a call to the IActiveScript::AddNamedItem method.
GetDocVersionString
Retrieves a host-defined string that uniquely identifies the current 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 the engine was running the script.
OnEnterScript
Informs the host that the scripting engine has begun executing the script code.
OnLeaveScript
Informs the host that the scripting engine has returned from executing script code.
Microsoft® Windows® Script Interfaces
IActiveScriptSite::GetDocVersionString HRESULT GetDocVersionString( BSTR *pbstrVersionString ); 24
Language Reference Previous Next
// address of document version string
Element
Element
25
Retrieves a host-defined string that uniquely identifies the current document version. If the related document has changed outside the scope of Windows Script (as in the case of an HTML page being edited with NotePad), the scripting engine can save this along with its persisted state, forcing a recompile the next time the script is loaded. • 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. Language Reference Previous Next
Microsoft® Windows® Script Interfaces
IActiveScriptSite::GetItemInfo
HRESULT IActiveScriptSite::GetItemInfo( LPCOLESTR pstrName, // address of item name DWORD dwReturnMask, // bit mask for information retrieval IUnknown **ppunkItem, // address of pointer to item's IUnknown ITypeInfo **ppTypeInfo // address of pointer to item's ITypeInfo ); Allows the scripting engine to obtain information about an item added with the IActiveScript::AddNamedItem method. • 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 engine should request the minimum amount of information possible because some of the return parameters (for example, ITypeInfo) can take considerable time to load or generate. Can be a combination of the following values: Value
Meaning
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 the given item. The scripting engine can use the IUnknown::QueryInterface method to obtain the IDispatch interface for the item. This parameter receives NULL if dwReturnMask does not include the SCRIPTINFO_IUNKNOWN value. Also, it receives NULL if there is no object associated with the item name; this mechanism is used to create a simple class when the named item was added with the SCRIPTITEM_CODEONLY flag set in the IActiveScript::AddNamedItem method. Element
25
26
Element
ppTypeInfo [out] Address of a variable that receives a pointer to the ITypeInfo interface associated with the item. This parameter receives NULL if dwReturnMask does not include the SCRIPTINFO_ITYPEINFO value, or if type information is not available for this item. If type information is not available, the object cannot source events, and name binding must be realized with the IDispatch::GetIDsOfNames method. Note that the ITypeInfo interface retrieved describes the item's coclass (TKIND_COCLASS) because the object may support multiple interfaces and event interfaces. If the item supports the IProvideMultipleTypeInfo interface, the ITypeInfo interface retrieved is the same as the index zero ITypeInfo that would be obtained using the IProvideMultipleTypeInfo::GetInfoOfIndex method. This method retrieves only the information indicated by the dwReturnMask parameter; this improves performance. For example, if an ITypeInfo interface is not needed for an item, it is simply not specified in dwReturnMask. Microsoft® Windows® Script Interfaces
IActiveScriptSite::GetLCID
Language Reference Previous Next
HRESULT GetLCID( LCID *plcid // address of variable for language identifier ); Retrieves the locale identifier associated with the host's user interface. The scripting engine uses the identifier to ensure that error strings and other user-interface elements generated by the engine appear in the appropriate language. • 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 by the scripting engine. If this method returns E_NOTIMPL, the system-defined locale identifier should be used. Microsoft® Windows® Script Interfaces
IActiveScriptSite::OnEnterScript
Language Reference Previous Next
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, if the script calls an object that then fires an event handled by the scripting engine, the scripting engine must call IActiveScriptSite::OnEnterScript before executing the event, and must call the IActiveScriptSite::OnLeaveScript method after executing the event but before returning to the object that fired 26
Element
Element
27
the event. Calls to this method can be nested. Every call to this method requires a corresponding call to IActiveScriptSite::OnLeaveScript. Microsoft® Windows® Script Interfaces
IActiveScriptSite::OnLeaveScript
Language Reference Previous Next
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 the scripting engine. For example, if the script calls an object that then fires an event handled by the scripting engine, the scripting engine must call the IActiveScriptSite::OnEnterScript method before executing the event, and must call IActiveScriptSite::OnLeaveScript after executing the event before returning to the object that fired the event. Calls to this method can be nested. Every call to IActiveScriptSite::OnEnterScript requires a corresponding call to this method. Microsoft® Windows® Script Interfaces
IActiveScriptSite::OnScriptError
Language Reference Previous Next
HRESULT IActiveScriptSite::OnScriptError( IActiveScriptError *pase // address of error interface ); Informs the host that an execution error occurred while the engine was running the script. • Returns S_OK if the error was correctly handled, or an OLE defined error code otherwise. pase [in] Address of the error object's IActiveScriptError interface. A host can use this interface to obtain information about the execution error. Microsoft® Windows® Script Interfaces
IActiveScriptSite::OnScriptTerminate
Language Reference Previous Next
HRESULT OnScriptTerminate( VARIANT *pvarResult, // address of script results EXCEPINFO *pexcepinfo // address of structure with exception informat ); 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 the script terminated, or NULL if no exception was generated. The scripting engine calls this method before the call to the IActiveScriptSite::OnStateChange method, with the SCRIPTSTATE_INITIALIZED flag set, is completed. This method can be used to return completion Element
27
28
Element
status and results to the host. Note that many script languages, which are based on sinking events from the host, have life spans that are defined by the host. In this case, this method may never be called. Microsoft® Windows® Script Interfaces
IActiveScriptSite::OnStateChange
Language Reference Previous Next
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 a description of the states. Microsoft® Windows® Script Interfaces
IActiveScriptSiteWindow
Language Reference Previous Next
This interface is implemented by hosts that support a user interface on the same object as IActiveScriptSite. Hosts that do not support a user interface, such as servers, would not implement the IActiveScriptSiteWindow interface. The scripting engine accesses this interface by calling QueryInterface from IActiveScriptSite. Methods in Vtable Order Method
Description
GetWindow
Retrieves the window handle that can act as the owner of a pop-up window that the scripting engine must display.
EnableModeless
Causes the host to enable or disable its main window as well as any modeless dialog boxes.
Microsoft® Windows® Script Interfaces
IActiveScriptSiteWindow::EnableModeless
Language Reference Previous Next
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
Element
Element
29
Microsoft® Windows® Script Interfaces
IActiveScriptSiteWindow::GetWindow
Language Reference Previous Next
HRESULT GetWindow( HWND *phwnd // address of variable for window handle ); Retrieves the handle to a window that can act as the owner of a pop-up window that the scripting engine must display. • 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. Language Reference Previous Next
Microsoft® Windows® Script Interfaces
Enumerations
This section describes the enumerations used by Windows Script engines. ♦ SCRIPTSTATE ♦ SCRIPTTHREADSTATE Language Reference Previous Next
Microsoft® Windows® Script Interfaces
SCRIPTSTATE typedef enum tagSCRIPTSTATE { SCRIPTSTATE_UNINITIALIZED SCRIPTSTATE_INITIALIZED SCRIPTSTATE_STARTED SCRIPTSTATE_CONNECTED SCRIPTSTATE_DISCONNECTED SCRIPTSTATE_CLOSED } SCRIPTSTATE;
= = = = = =
0, 5, 1, 2, 3, 4
Contains named constant values that specify the state of a scripting engine. This enumeration is used by the IActiveScript::GetScriptState, IActiveScript::SetScriptState, and IActiveScriptSite::OnStateChange methods. SCRIPTSTATE_UNINITIALIZED Script has just been created, but has not yet been initialized using an IPersist* interface and IActiveScript::SetScriptSite. SCRIPTSTATE_INITIALIZED Script has been initialized, but is not running (connecting to other objects or sinking events) or executing any code. Code can be queried for execution by calling the IActiveScriptParse::ParseScriptText method. SCRIPTSTATE_STARTED Script can execute code, but is not yet sinking the events of objects added by the IActiveScript::AddNamedItem method. SCRIPTSTATE_CONNECTED Script is loaded and connected for sinking events. SCRIPTSTATE_DISCONNECTED Script is loaded and has a run-time execution state, but is temporarily disconnected from sinking events. Element
29
30
Element
SCRIPTSTATE_CLOSED Script has been closed. The scripting engine no longer works and returns errors for most methods.
30
Element
View more...
Comments