Introduction to JScript
1 © 2011 ANSYS, Inc. November 29, 2012
JScript Training Objective
1. What is JScript?
2. How to write JScript program?
3. How to use JScript debugger?
2 © 2011 ANSYS, Inc. November 29, 2012
SR Slide
No. Topics No.
01 Introduction 4
02 Basic Syntax 7
03 Variables 8
04 Arrays 9-10
05 String 11-12
06 Operators 13
07 Conditionals & Simple Loops 14-16
08 Exception Handling 17
09 Functions 18
10 Objects 20-25
11 COM and Active X 26-27
12 Jscript Debugging 29-32
13 Online References 33
3 © 2011 ANSYS, Inc. November 29, 2012
Introduction - What is JScript?
A Scripting language:
A scripting languae is a simple programming language desinged to enable
computer users to write usefule programs easily. Scripting languages, are
interpreted, meaning that they are not compiled to any particular machine or
operating system. This feature makes them platform independent.
Originally built for use on Web pages
• HTML-friendly
• Lightweight
• Interpreted
Syntax similar to C and Java
JScript, JavaScript and Java
– We use “JavaScript” and “JScript” interchangeably
– JScript is Microsoft’s implementation of JavaScript
– Microsoft adds Windows-specific capabilities
– JavaScript is NOT Java
References:
– [Link]
– [Link]
4 © 2011 ANSYS, Inc. November 29, 2012
JScript Programming
5 © 2011 ANSYS, Inc. November 29, 2012
JScript Programming
Jscript Syntax
6 © 2011 ANSYS, Inc. November 29, 2012
Basic Syntax
Semicolon
– Each statement must end with a semicolon (;)
– Multiple statements may share a line
Comma
– A comma separates entries on a line
Whitespace
– Whitespace is ignored when possible
Comments
– Syntax # 1: // Comment
– Text after // is ignored in a single line
– Syntax # 2: /* Comment */
– Text between /* */ pairs is ignored
Case-sensitivity
– JScript is case-sensitive
– Variable names may mix upper- and lower-case
– Calling code must match the case exactly
JScript keywords are case-sensitive too
Using a good editor helps a lot!
7 © 2011 ANSYS, Inc. November 29, 2012
Variables
A variable:
– Is declared with the keyword “var”
• For global variables and local variables
• No “var” for function arguments
– The name must start with an alphabetic
character
– Can be any length
Variable Types:
– Number
– String
– Boolean
– Array
– Objects
JScript doesn’t enforce variable types
– A variable can change type
8 © 2011 ANSYS, Inc. November 29, 2012
Arrays (1)
One-Step array allocation
– var primes = [2, 3 ,5 7, 11, 13];
– var names = *“Joe”, “Jane”, “John”, “Juan”+;
– No trailing comma after last element
Two-step array allocation
– var names = new Array(4);
names*0+ = “Joe”;
…..
names*3+ = “Juan”;
Index starts with 0
for (var i=0; i<[Link]; i++)
{
doSomethingWith(names[i]);
}
9 © 2011 ANSYS, Inc. November 29, 2012
Arrays (2)
Arrays can be sparse
– var names = new Array();
names*0+= “Joe”
names*10000+= “Juan”
Arrays can be resized
– Regardless of how arrays are created, you can do:
• [Link] = someNewLenght; // you can reassign the new length
• myArray[anyNumber] = someNewValue;
• [Link](someNewValue);
Arrays have mothods
– push, pop, join, reverse, sort, concat, slide, splice etc. (see
[Link]/jsref/ for more detail)
10 © 2011 ANSYS, Inc. November 29, 2012
String (1)
You can use double or single quotes
– var names = *“Joe”, ‘Jane’, “John”, ‘Juan’+;
You can access length property
– E.g. “football”.lenght returns 8
Numbers can be converted to strings
– Automatic conversion during concatenations
var val = 3 + “abc” + 5; // Result is “3abc5”
– Conversion with fixed precision
var n= 123.4567;
var val=[Link](2); //Result is 123.46
Strings can be compared with == & === [=== and !== are strict comparison operators]
– “foo” == ‘foo’ returns True
– ‘5’ == 5 returns True
– ‘5’ === 5 returns False
– ‘5’ === ‘5’ returns True
Strings can be converted to numbers
– var I = parseInt(“37 blah”); // Result is 37 – Ignores ‘blah’
– var d = parseFloat (“6.02 blah”); // Result is 6.02 – Ignores ‘blah”
11 © 2011 ANSYS, Inc. November 29, 2012
String (2)
Simple methods
– [Link](index); Returns the character at the specified index
– [Link](); [Link](); Returns the position of the first and last
found occurrence of a specified value in a string
– [Link](); : Extracts the characters from a string, between two specified
indices
– [Link](); Converts a string to lowercase letters
– [Link](); Converts a string to uppercase letters
– [Link](“old",“new"); Return a string where “old" is replaced with “new"
– [Link](/ain/g); Search a string for "ain“, The result of this will be an array
with the values:
– [Link](" "); Split a string into an array of substrings. The result of this will be
an array with the values
– For more detail please vist : [Link]
12 © 2011 ANSYS, Inc. November 29, 2012
Operators
Arithmetic operators
– Add (+), subtract (-), multiply (*), divide (/)
Assignment operators
– Simple assignment
– Multiple assignments to same value
– Compound assignment
Unary operators
– Increment number (+ +)
– Decrement number (- -)
– Prefix: adjust the number first, then evaluate it
– Postfix: evaluate the number first, then adjust it
Logical operators
– And (&&) , Or (||) , Not (!=)
Relational operators
– Comparisons return Boolean values
– Equal to, not equal to
– Less than, greater than
– Less than or equal to, greater than or equal to
Operators and strings
– Use assignment and addition operators to concatenate strings
– JScript will convert other variables to strings as needed
13 © 2011 ANSYS, Inc. November 29, 2012
Conditionals and Simple Loops (1)
If-Else conditional
– The condition is wrapped by parentheses ()
– “if” and “else” keywords are lowercase
– Use braces to group statements that are to
be executed together
– A block can include zero, one or more
statements
– For a single statement block, braces are
optional
• Conditions
– Boolean variable
– String Comparison
– Complex comparison
• Nesting
14 © 2011 ANSYS, Inc. November 29, 2012
Conditionals and Simple Loops (2)
variable initialization
For loop
condition check
– Same syntax as in C and Java
– Has three components, separated by variable change
semicolon wrapped by parentheses
• variable initialization
– Any statements here are executed once
before the loop starts
– By convention, the loop variable is initialized
here
• condition check
– The condition is checked at the beginning of
each loop
– The loop repeats while the condition is true
• variable change
– This statement is executed at the end of each
loop
– By convention, the loop variable is adjusted
here
15 © 2011 ANSYS, Inc. November 29, 2012
Conditionals and Simple Loops (3)
Switch-Case conditional
– An alternate way of doing multiple “if”
checks on a single variable
– “switch” ,“case” ,“break” and “default”
keywords are lowercase
– Typically used with strings or integers
– Good for discrete sets
– Not good for open ended sets
– The break statement exits the switch-
case check
– Without the break, flow continues to the
next case
– The default statement is optional
• Use it for clarity
– The case statements may be grouped if
they have identical code blocks
16 © 2011 ANSYS, Inc. November 29, 2012
Exception Handling
try…catch statement
– Used when an exception or error may occur.
– If the “try” statement fails, the “catch” statement is executed.
17 © 2011 ANSYS, Inc. November 29, 2012
Functions
Also referred to as
– Subroutines
– Procedures
– Methods
A function declaration:
– Is identified by the keyword “function”
– Needs parentheses () to define the argument list
– Needs braces {} to define the function block
– A function name must start with an alphabetic
character; can be of any length
– Can take arguments
– Can return a value
Arguments are sometimes called “parameters”
A function may return a single value
– A function is not required to return a value
– The return value may be any valid variable type
18 © 2011 ANSYS, Inc. November 29, 2012
JScript Programming
Class and Objects in
WB Jscript
19 © 2011 ANSYS, Inc. November 29, 2012
Objects – Introduction
name = Mary
An object: age = 30
Is a complex variable that has: class: Person
– Data (often called properties) name = John
property: name
– Functions (often called methods) age = 55
property: age
Is an instance of a class name = Susan
– A class defines a category of objects age = 22
Syntax
– JScript uses a “dot” notation // Properties
• object . property [Link] = “Mary”;
• The dot connects the object to its properties and var newPerson = [Link];
methods [Link] = “John”;
• No whitespace!
• Property and method names are case-sensitive!
// Methods
• Properties:
[Link]();
– A property is any valid variable type [Link]( “New York” );
• Methods:
– Methods follow the same rules as functions
20 © 2011 ANSYS, Inc. November 29, 2012
Objects - Contructors (Example)
Constructors
– A ‘Constructor’ is just a Function that assigns to ‘this’
– This is not exact class definition in Jscript
– The closet you get is when you define a function that assigns values to properties
in “this” reference
– Calling this funciton using “new” binds “this” to a new “Object”
– For example, following is simple constructor for a “Ship” case,
– The Object can be created using,
21 © 2011 ANSYS, Inc. November 29, 2012
Objects - Example (Using Methods)
Example (Circle Class )
Add more discription
Creating new Objects and use of methods
22 © 2011 ANSYS, Inc. November 29, 2012
Objects – Example (summary)
Defining properties
– A constructor has a special piece of data
called this
– this points to your new object
– Use this to define properties for your class
Defining methods
– First write a method as a normal function
– Use this to assign the method to your class
Defining relationships between objects
– An object may “own” another object
– Parent-child relationships are common
– Use properties to define the association
– Use multiple “dots” to chain several
objects together on one line
23 © 2011 ANSYS, Inc. November 29, 2012
Objects - Built-in Classes
JScript has built-in classes to help with:
– String manipulation
– Array handling
– Mathematical operations
You can define your own classes in Jscript
– Built-in Classes
• String class
– A string variable is automatically an
instance of the String class
• Math class
• Date class
• Array class
You can create the full-fledged object
yourself with the new keyword
– new allocates and initializes an object of
the class you choose
24 © 2011 ANSYS, Inc. November 29, 2012
Objects - Collections
A Collection:
– Is a custom object that holds a list of other objects
• Like a read-only Array
– Is frequently used in the Workbench API
Collection properties:
– Count
• Returns the number of items in the collection
• This is a read-only property
Collection methods:
– Item ( index )
• Returns the object at the index specified
• Collection item counting starts at 1, not 0! A sample code
• “Item” is optional showing how to
access the Geometry
Collection in
Mechanical
25 © 2011 ANSYS, Inc. November 29, 2012
COM Classes (1)
COM is:
– A programming layer provided by Microsoft
– Accessible from any Microsoft language, plus others
– Widely used throughout Windows and Windows applications
Why COM:
– JavaScript only knows about JavaScript classes
– Microsoft’s JScript can handle COM classes as well
– Workbench functionality is compiled C++ for performance
– COM lets us access the Workbench COM classes from JScript
• And from other languages too
ActiveXObject class
– ActiveX is a Microsoft term for a Web-enabled COM class
– JScript lets you create an ActiveX object with the new keyword
26 © 2011 ANSYS, Inc. November 29, 2012
COM Classes (2)
Microsoft provides ActiveX
objects for accessing:
– Files
– Folders
– Registry
– Command line
– Interacting with MS Office
applications
– …
Workbench provides ActiveX
objects for creating:
– Callbacks
– Dialog boxes
– Various Controls
– …
27 © 2011 ANSYS, Inc. November 29, 2012
Jscript Introduction
JScript Debugging
28 © 2011 ANSYS, Inc. November 29, 2012
Prerequisites
User should have Visual
Studio Professional 2008
or 2010 installed on
system for debugging
Enable JIT Debugger
– Open “regedit”
– Go to: (HKEY_CURRENT_USER
> Software > Microsoft
> Windows Script>
Settings)
– Set the JITDebug (Just in
Time Debug) key to 1
Now you are ready to debug!
29 © 2011 ANSYS, Inc. November 29, 2012
Standalone JScript Debugging
Add the following line on the top of
the JS file
– debugger;
Run the JS file from command
prompt
– Open a command prompt
– Run: [Link] //d <path to JS file>
(e.g. [Link] //d
“C:\Temp\[Link]”)
– Select the available debugger
Using the Debugger
– Step into the code line by line (F10)
– Attach Break Points as required and
use Continue till the break point (F5)
– Add variables to the Watch window
to check their values
30 © 2011 ANSYS, Inc. November 29, 2012
JScript Debugging in Workbench
Run the JS file in Mechanical:
DS_ObjectInvestigator.js from
Tools Run Macro...
Select the available debugger
– In the debugger window
• Step into the code line by line (F10)
• Attach Break Points as required and use
Continue till the break point (F5)
• Add variables to the Watch window to check
their values
31 © 2011 ANSYS, Inc. November 29, 2012
Exploring the Selected Object
Two types of informations are available in
the debugger :
– [Methods]
– Properties
The [methods] are used to add specific
items in the DS Tree.
– Name correspond to what you want to do
– Value is the syntex to be used
– Type give information on input parameters
32 © 2011 ANSYS, Inc. November 29, 2012
Online References
JScript Tutorial (language Syntax)
– [Link]
– [Link]
Jscript API references (builtin Ojbects)
– [Link]
– [Link]
– [Link]
– [Link]
– [Link]
Some Link on Visual Studio Debugger tips and tricks
• Notes: The idea is to just get yourself familiarize with the debugging functionality;
– [Link]
– [Link]
– [Link]
– [Link]
33 © 2011 ANSYS, Inc. November 29, 2012