Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Jscript part1

1,982 views

Published on

Published in: Technology
  • Be the first to comment

Jscript part1

  1. 1. Girish Srivastava girish092.ch@gmail.com 1 10/15/2013
  2. 2. Objective  Introduction to jscript.  Difference between Jscript, JavaScript and        2  VBScript. Versions. Programming logic techniques of the Jscript. Writing Jscript statements and coding. OOPs Concept. Understanding JScript objects. Working with methods . The JScript object hierarchy. Practice Examples 10/15/2013
  3. 3. Topics has to be covered… Day 1 Introduction to jscript. Javascript vs jscript and other scripting languages. Versions. Day 2 OOPs Concept Understanding JScript objects Array handling Exception Handling Array Object Error Object The role of objects in JScript programming Programming logic techniques Working with methods and of the Jscript properties Writing Jscript statements and The JScript object hierarchy coding String Handling Object Literals 3 10/15/2013
  4. 4. What Is script ?  In computer programming, a script is a program 4 or sequence of instructions that is interpreted or carried out by another program rather than by the computer processer (as a compiled program is).  A script is sometimes used to mean a list of operating system commands that are pre-stored in a file and performed sequentially by the operating system's command interpreter whenever the list name is entered as a single command.  Multimedia development programs use "script" to mean the sequence of instructions that you enter 10/15/2013 to indicate how a multimedia sequence of files will
  5. 5. What Is scripting language ?  A scripting language is a form of programming 5 language that is usually interpreted rather than compiled.  Conventional programs are converted permanently into executable files before they are run. In contrast, programs in scripting language are interpreted one command at a time.  Scripting languages can be used to create specialized GUIs (graphical user interfaces) and forms that enhance the convenience of search engines, Web-based e-mail and e-commerce.  For Example: C 10/15/2013 shell, JavaScript, Jscript, Perl, PHP, Python, VBS
  6. 6. Introduction of JScript  JScript is a scripting language from Microsoft that is expressly designed for use within Web pages. It adheres to the ECMAScript standard and is basically Microsoft's equivalent to Netscape's earlier and more widely used JavaScript.  ECMAScript (European Computer Manufacturers Association Script)  ECMAScript is a standard script language, developed with the cooperation of Netscape and Microsoft and mainly derived from Netscape's JavaScript, the widelyused scripting language that is used in Web pages to affect how they look or behave for the user.  ECMAScript is object-oriented and conceived as a core language to which can be added the objects of any 6 specific domain or context such as the idea of a 10/15/2013
  7. 7. Using JScript  JScript is an interpreted, object-based scripting language. Although it has fewer capabilities than fullfledged 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.  You cannot write stand-alone applications in it, and it has no built-in support for reading or writing files.  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. 7 10/15/2013
  8. 8. JavaScript Vs JScript Vs VBScript  JavaScript  JavaScript is a light weight and very simple Scripting Language that has Object Oriented capabilities and most importantly it is a cross platform Scripting Language.  These scripts can be integrated directly into the HTML code.  JavaScript was originally developed by Netscape.  Here is a simple example showing a text in a web page using JavaScript. <html> <body> <script type="text/javascript"> { document.write("Hello JavaScript"); } </script> </body> </html> 8 10/15/2013
  9. 9.  Jscript  Actually JScript is just the Microsoft's version of JavaScript. Microsoft thought of implementing their own version of JavaScript and they named it as JScript.  But in some situations JScript is not behaving like JavaScript.  Take a simple example: Let's declare a variable called temp in JavaScript code and create a object within the page having the field id as "temp". var temp = 'Hello'; And trying to set the value of object temp in the page to the value of variable temp. document.getElementById('temp').innerHTML = temp; 9 10/15/2013
  10. 10. Cont…  In the above example, is working fine, but the JScript gives a error.  reason behind this is, in here JScript does not recognize the difference between var temp and document.getElementById('temp'). So he treats as both of them are referring to one single object. But JavaScript recognises the temp variable and the object within the page having id "temp" as two entirely separate fields.  So this is a one significant difference between JavaScript and JScript.  here is a simple example showing a text in a web page using JScript. 10 <html> <body> <script type="text/JScript"> { document.write("Hello JScript"); } </script> </body> </html> 10/15/2013
  11. 11. VBScript  VBScript is Microsoft's Scripting Language just as JScript.  It is actually a child of Microsoft's Visual Basic for use with web pages and other applications that uses Microsoft ActiveX controls.  VBScript is very similar to JavaScript, but VBScript syntaxes are more similar to Visual Basic.  Comparison of JavaScript and VBScript 11 10/15/2013
  12. 12. Cont… Similarities Differences Both languages are easy to learn and do not require any expensive development tools. JavaScript is the default scripting language for browsers but VBScript must be specified as the scripting language. Both can be used to enhance web pages. JavaScript has cross-platform support from all popular browsers while VBScript is supported MS IE only. Both can abuse and run malicious scripts on clients' machines. JavaScript is case sensitive but VBScript is not this would not be prone to as many syntax errors like missing > JavaScript uses the same character for concatenation as it does for addition (the + character) while the '&' concatenating character is used in VBScript. This is another source of errors in JavaScript. 12 10/15/2013
  13. 13. Cont…  Here is a simple example showing a text in a web page using VBScript. <html> <body> <script type="text/vbscript"> { document.write("Hello VBScript"); } </script> </body> </html> 13 10/15/2013
  14. 14. Version  The following table lists the version of Microsoft JScript implemented by host applications. Host application JScript version Internet Explorer 3.0 Internet Information Server 3.0 2.0 Internet Explorer 4.0 3.0 Internet Information Server 4.0 3.0 Visual Studio 6.0 4.0 Internet Explorer 5.0 5.0 Internet Explorer 5.01 5.1 Windows 2000 5.1 Internet Explorer 5.5 5.5 Internet Explorer 6.0 5.6 Windows XP (through SP2) 5.6 Internet Explorer 7.0 5.7 Windows XP SP3 14 1.0 5.7 Windows Vista 5.7 Internet Explorer 8.0 5.8 10/15/2013
  15. 15. Applications Fundamentals  Practical Learning: Adding the Compiler to the Path  Start Windows Explorer and locate the folder where your jsc application is installed. Here is an example: 15 10/15/2013
  16. 16. Cont…  Click Start -> Control Panel  Double-click System  In the System Properties dialog box, click the Advanced     16 tab and click Environment Variables In the System Variables section, click Path and click Edit Press End or get to the end of the string Type ; followed by the complete path to the compiler. Click OK on each dialog box 10/15/2013
  17. 17. Practical Learning: Introducing Jscript Code  Start Notepad and in it, type print("Welcome to the         17 Wonderful World of JScript "); To save the file, on the main menu, click File -> Save Select and display the C: drive in the Save In combo box Click the Create New Folder button Type JScript Lessons Press Enter twice or display the new folder in the Save In combo box Click the Create New Folder button again Type Exercise1 and press Enter twice or display the new folder in the Save In combo box Save the file as exercise.js 10/15/2013
  18. 18. Practical Learning: Compiling an Application  To test the application, open the Command Prompt and change to the folder in which you created the Jscript file. 18 •Type jsc exercise.js and press Enter •When the program has finished compiling, type exercise and press Enter 10/15/2013
  19. 19. A Custom Name for an Executable  As mentioned above, if you compile your application by simply invoking the name of the script file that contains the code, an executable with the same name as the file would be created.  Fortunately, when compiling the file, you can specify the name you want for the executable.  jsc /out:ApplicationName File.js  you must first call the compiler as done previously. It must be followed by /out: which indicates that you are going to specify the name of the executable.  After the /out: factor, type the desired name that will hold the name of the new application instead of the name of the file.  Lastly, type the name of the file that contains the script and make sure you append its extension. 19 10/15/2013
  20. 20. To compile with debugging information using jsc  At the command prompt, type jsc /debug file.js The command compiles the program named file.js with the /debug option to produce the executable named file.exe and a file named file.pdb that contains debugging information. http://msdn.microsoft.com/enus/library/0h6706k6(v=vs.71).aspx Debugging JScript with Visual Studio http://msdn.microsoft.com/enus/library/bssx024s%28v=vs.80%29.aspx 20 10/15/2013
  21. 21. Programming logic techniques of the Jscript  Variables  Statements  Data types  Comments  Operators and its Precedence  Controlling Program flow  Jscript reserve words  Conditions and Loops 21 10/15/2013
  22. 22. Variables  A typical program uses various and different values. Some are used for display to the user. Some are requested from the user.  To manage these various values, the compiler reserves some sections of the computer memory to store them.  To declare a variable, type var, followed by a name for the variable, followed by a colon, and followed by a word that defines the type of value that would be stored in this memory space. ovar VariableName : DataType;  This means that, to declare a variable, you must 22 provide a name and specify the type of information the 10/15/2013 variable will carry.
  23. 23. Identifiers  An identifier is a word that is used to identify an entity in a program. There are rules you must follow when naming your variables. They are:  The first character must be a letter (a, b, c,…, z, A, B, C, …, or Z) or an underscore (_). Examples are _pages, country, or sound  After the first character, the name can contain letters, underscores, or digits (0, 1, 2, 3,…, or 9). Examples are number1, _page6, complete_sound  The complete name must not be one of the words reserved for the compilers own use 23 10/15/2013
  24. 24. Cont…  JScript is case-sensitive. This means that case, CASE, and Case are three different words. Based on these rules, avoid using the following reserved words to name your variables: abstract char default export break const do false byte continue double final for 24 boolean class delete extends function get if in new return super typeof while instanceof null sbyte switch uint with int package set this ulong interface private short throw ushort case debugger else finally implement s internal protected static true var catch decimal enum float import long public try void 10/15/2013
  25. 25. Comments And Escape Sequence  A comment is a line or paragraph of text that the compiler would not consider when examining the code of a program.  To display a comment on a line of text, start the line with two forward slashes //. Anything on the right side of // would be ignored. Here is an example:  // This line will be ignored. I can write in it anything I want  The above type of comment is used on only one line. You can also start a comment with /*. This type of comment ends with */.  Anything between this combination of /* and */ would not be read by the compiler. Therefore, you can 10/15/2013 use 25 this technique to span a comment on more than one
  26. 26. Escape Sequences  An escape sequence is a special character that displays non-visibly. For example, you can use this type of character to indicate the end of line, that is, to ask the program to continue on the next line.  An escape sequence is represented by a backslash character, , followed by another character or symbol. For example, the escape sequence that moves to the next line is n.  An escape can be included in single-quotes as in 'n'. It can also be provided in double-quotes as "n". 26 10/15/2013
  27. 27. Cont… Escape Sequence Name b Backspace t Horizontal Tab n New line v Vertical Tab f Form feed r Carriage return Causes a carriage return s Any Character Matches any white space character S Any Character Matches any non-white space character ' Single Quote Displays a single quote " Double Quote Displays a double quote Backslash Displays a backslash () h Character xhh 2-Digit Hex xhhhh 4-Digit Hex 27 Description Takes the cursor back by one space Takes the cursor to the next tab stop Takes the cursor to the beginning of the next line Performs a vertical tab Displays an ASCII character from an octal number Displays a hexadecimal number with two digits Displays a hexadecimal number with four 10/15/2013 digits
  28. 28. Data Types  A data type is a word that indicates the amount of memory needed to store the value of a variable.  As there are various types of values used in a program, there are also different data types. Some data types are meant to hold numbers. Some others are form particular values such as one being true or false.  In short, data types are specifications of how to handle variables. The interpreter needs to know how much memory he shall reserve for the data, and what can be done with these. 28 10/15/2013
  29. 29. Cont… Data Type Description Example Char a single character, enclosed in single quotation marks var c: char = ’a’; String a sequence of characters, enclosed in double quotation marks var s: String = "Hello"; Int a 32-bit integer value, ranging from 2.147.483.648 to 2.147.483.647 var i: int = 1; Uint a unsigned 32-bit integer, ranging from 0 to 4.294.967.295 var i: uint = 1; Boolean a boolean value that is either true or false var b: boolean = false; Double floating point number of double precision (about 15 digits) var d: double = 0.123; object representing a var date: Date 29 Date 10/15/2013
  30. 30. Type mismatch import System; var s: int = 3; s = s + 5; Console.WriteLine(s); s = "I’m not an integer!"; Console.WriteLine(s); import System; var s = 5; s = "I’m a string!"; s = s + 3; Console.WriteLine(s); NOTE: If you do not initialize a variable, i.e. if you declare a variable without setting it to a certain value, requesting the value will return NaN (Not a Number) or ”undefined”, depending on the context in which the variable was interpreted. For example, import System; var i; Console.WriteLine( "Value of i: " + i); Console.WriteLine( "Value of 2*i: " + 2*i); will produce the output ”Value of i: undefined” and ”Value of i: NaN”, 10/15/2013 30 because in the first case we have a type conversion to string, in the
  31. 31. Operators and Operands  An operation is an action performed on one or more values either to modify the value held by one or both of the variables, or to produce a new value by combining existing values.  Therefore, an operation is performed using at least one symbol and at least one value. The symbol used in an operation is called an operator. A value involved in an operation is called an operand.  A unary operator is an operator that performs its operation on only one operand. An operator is referred to as binary if it operates on two operands. 31 10/15/2013
  32. 32. JScript Operators Computational Description Symbol Unary negation - Increment Logical Description Bitwise Symbol Description Assignment Symbol Description Symbol Miscellaneous Description Symbol Logical NOT ! Bitwise NOT ~ Assignment = delete Delete ++ Less than < Bitwise Left Shift << Compound Assignment OP= typeof Typeof Decrement -- Greater than > Bitwise Right Shift >> Multiplicati on * Less than or equal to <= Unsigned Right Shift >>> Division / Greater than or equal to >= Bitwise AND & Modulo arithmetic % Equality == Bitwise XOR ^ Addition + Inequality != Bitwise OR | Subtraction - Logical AND Void && Logical OR || Conditional (trinary) ?: Comma 32 void , Identity === 10/15/2013
  33. 33. Operator Precedence Operator Description . [] () Field access, array indexing, and function calls ++ -- - ~ ! typeof new void delete Unary operators, return data type, object creation, undefined values */% Multiplication, division, modulo division +-+ Addition, subtraction, string concatenation << >> >>> Bit shifting < <= > >= Less than, less than or equal to, greater than, greater than or equal to == != === !== Equality, inequality, identity, nonidentity & Bitwise AND ^ Bitwise XOR | Bitwise OR && Logical AND || Logical OR ?: Conditional = OP= Assignment, assignment with operation 33 , Multiple evaluation 10/15/2013
  34. 34. Sample Example import System; var a: boolean = true; var b: boolean = false; Console.WriteLine("a AND b = " + (a && b)); Console.WriteLine("a OR b = " + (a || b)); Output: ”a And b = false” ”a OR b = true” 34 10/15/2013
  35. 35. Program Flow  if..else-statements import System; var i=Math.random(); if (i<0.5) Console.WriteLine("This number " + i + " is smaller than 0.5"); else Console.WriteLine("This number " + i + " is larger than or equals 0.5");  Here, the code following the if-condition is executed if the condition is true, and the code following the else-statement is executed if the statement is false. This is what you should notice: 35 • the boolean expression has to be set in parenthesis • the if-clause here only consists of one command. It has to be closed by a semicolon • the else-clause also only consists of one command and has10/15/2013 to be closed by a semicolon
  36. 36. for-Loops  The for-loops allow to repeat a command or block of code for a certain time. Usually, a counter is counted up until a certain condition does not hold any more. import System; var i; for (i=1;i<10;i++) Console.WriteLine("This is the " + i + ". line.");  for..in-Loops import System; var weekday = ["monday", "tuesday", "wednesday", "thursday"]; var j; for (j in weekday) Console.WriteLine(weekday[j]); 36 10/15/2013
  37. 37. while-Loops  The while-loops are similar to the for-loops, but the header of the while loop has no section for initializing and no section for incrementation, but just the section for a comparison, the while-condition. 37 import System; var steps = 10; while (steps >= 1) { if (steps > 1) Console.WriteLine(" There are" + steps + " to do."); else Console.WriteLine("Now there is only one more step"); steps--; } 10/15/2013
  38. 38. do...while  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. 38 import System; var x = 0; do { x = Console.WriteLine("What is my favourite number?", x); } while ((x != 42) && (x != null)); if (x == null) Console.WriteLine("You gave up!"); else 10/15/2013
  39. 39. Functions  A function is a piece of code that is encapsulated and can be executed by calling the command under which the function is defined.  JScript supports two kinds of functions: those that are built into the language, and those you create yourself. o Special Built-in Functions  The JScript language includes several built-in functions. Some of them let you handle expressions and special characters, and convert strings to numeric values.  For example, escape() and unescape() are used to convert characters that have special meanings in HTML code, characters that you cannot just put directly into text. For example, the angle brackets, "<" and ">", delineate HTML tags. 39 10/15/2013
  40. 40. Cont… •Escape function: Encodes String objectsthese  The escape function takes as its argument any of so special characters, and all computers. they can be read onreturns the escape code for the character. Each escape code consists of a percent sign •The escape method returns a string value (%) followed by a two-digit number. (in Unicode format) that contains the  The unescape function is the exact inverse. It takes as contents ofacharstring. All spaces, sign and a its argument string consisting of a percent punctuation, accented characters, and any other two-digit number, and returns a character. non-ASCII characters are replacedwhich %xx  Another useful built-in function is eval(), with evaluates where mathematical expression encoding, any validxx is equivalent to thethat is presented in string form. The eval() function character. hexadecimal number representing thetakes one argument, the expression to be evaluated. For example,anExpression = "6 * 9returned as "%20.“ a space is % 7"; • var • var total = a value greater than 255 the •Characters with eval(anExpression); // Assigns the value 5 toare variable total. stored using yetAnotherExpression = "6 * (9 % 7)"; • var the %uxxxx format. 10/15/2013 40 • total = eval(yetAnotherExpression); //Assigns the encoded •Unescape Method: Decodes String objectsvalue 12 to
  41. 41. Creating Your Own Functions  You can create your own functions and use them where you need them. A function definition consists of a function statement and a block of JScript statements.  For Example: import System; function factorial(n) { var i; var f=1; for (i=1;i<=n;i++) f=f*i; return f; } Console.WriteLine(factorial(8)); 41 10/15/2013
  42. 42. Wait functions 42 // The namespace "System.Threading" provides the "Thread"-class which // includes the "Sleep"-method import System.Threading; var i; for (i=0; i<=5; i++) { // Wait for 500 ms Thread.Sleep(500); // Display the variable i in the Output window System.Console.WriteLine("Number: "+i); } 10/15/2013
  43. 43. JScript Objects  JScript objects are collections of properties and methods.  A method is a function that is a member of an object, and a property is a value or set of values (in the form of an array or object).  Objects as Arrays  In JScript, objects and arrays are handled identically.  You can refer to any of the members of an object : o either by name (using the name of the object, followed by a period, followed by the name of the property) o or by its array subscript index.  All objects in JScript support "expando" properties, or properties that can be added and removed dynamically at run time. 43 • var myObj = new Object(); 10/15/2013
  44. 44. Cont…  The fact that objects can have other objects as properties lets you generate arrays with more than one subscript, which are not directly supported. The following code creates a multiplication table for values from 0 times 0 through 16 times 16. var multTable = new Array(17); // Make the shell that will become the table. for (var j = 0; j < multTable.length; j++) { // Prepare to fill it with rows. var aRow = new Array(17); // Create a row. for (var i = 0; i < aRow.length; i++) { // Prepare to fill the row. aRow[i] = (i + " times " + j + " = " + i*j); // Make and place one value. } multTable[j] = aRow; // Put the filled row into the table. Console.WriteLine(multTable[j]); } 44 10/15/2013
  45. 45. JScript Reserved Keywords  JScript has a number of reserved keywords that you cannot use as identifiers.  These words come in three types: JScript reserved keywords, future reserved words, and words to avoid.  Reserved words have a specific meaning to the JScript language, as they are part of the language syntax. Using a reserved word causes a compilation error when loading your script.  JScript also has a list of future reserved words. These words are not currently part of the JScript language, although they are reserved for future use. 45 10/15/2013
  46. 46. Cont…  Reserved Words break delete function return typeof Case Do If Switch Var Catch Else In This Void Continue False Instanceof Throw While Debugger Finally New True With Default For Null try •Future Reserved Words Abstract Double Goto Boolean Enum Implement Package s Super Byte Export Import Private Synchronize d Char Extends Int Protecte d Throws Public Transient 46 Class Final Interface Native Static 10/15/2013
  47. 47. Recursion  Recursion is an important programming technique. It is used to have a function call itself from within itself.  One handy example is the calculation of factorials. The factorials of 0 and 1 are both defined specifically to be 1.  The factorials of larger numbers are calculated by multiplying 1 * 2 * ..., incrementing by 1 until you reach the number for which you're calculating the factorial.  Recursion and iteration (looping) are strongly related anything that can be done with recursion can be done with iteration, and vice-versa. 47 10/15/2013
  48. 48. Cont…  Here is the factorial function again, this time written in JScript code. 48 // Function to calculate factorials. If an invalid // number is passed in (ie, one less than zero), -1 // is returned to signify an error. Otherwise, the // number is converted to the nearest integer, and its // factorial is returned. function factorial(aNumber) { aNumber = Math.floor(aNumber); // If the number is not an integer, round it down. if (aNumber < 0) { // If the number is less than zero, reject it. return -1; } if (aNumber == 0) { // If the number is 0, its factorial is 1. return 1; } else return (aNumber * factorial(aNumber - 1)); // Otherwise, recurse until done. 10/15/2013 }
  49. 49. Variable Scope  JScript has two scopes: global and local.  If you declare a variable outside of any function definition, it is a global variable, and its value is accessible and modifiable throughout your program.  If you declare a variable inside of a function definition, that variable is local.  It is created and destroyed every time the function is executed; it cannot be accessed by anything outside the function.  A local variable can have the same name as a global variable, but it is entirely distinct and separate.  Consequently, changing the value of one variable has no effect on the other. Inside the function in which the 10/15/2013 49 local variable is declared, only the local version has
  50. 50. Example: 50 var aNumber = 100; var withAdditive = 0; withAdditive += aNumber; // withAdditive is now 100. tweak(); withAdditive += aNumber; // withAdditive is now 200. function tweak() { var newThing = 0; // Explicit declaration of the newThing variable. aNumber = 42; if (false) { var aNumber; // This statement is never executed. aNumber = "Hello!"; // This statement is never 10/15/2013 executed.
  51. 51. Special Characters  JScript provides special characters that allow you to include in strings some characters you cannot type directly.  Each of these characters begins with a backslash. The backslash is an escape character you use to inform the JScriptEscape Sequence the next character is special. interpreter that Character b n Line feed (new line) r Carriage return t Horizontal tab (Ctrl-I) ’ Single quotation mark ” Double quotation mark 51 Backspace Backslash 10/15/2013
  52. 52. Exception Handling  try...catch.finally Statement  The try...catch.finally statement provides a way to handle some or all of the possible errors that may occur in a given block of code, while still running code.  If errors occur that the programmer has not handled, Jscript simply provides its normal error message to a user, as if there was no error handling. 52 try { tryStatements //Required. Statements where an error can occur. } catch(exception){ catchStatements //Required. Any variable name. The initial value of exception is the value of the thrown error. } //Optional. Statements to handle errors occurring in the associated tryStatements. finally { 10/15/2013 finallyStatements //Optional. Statements that are
  53. 53. Example  The following example shows how JScript exception handling works. 53 try { print("Outer try running.."); This produces the following output try { print("Nested try running..."); Outer try running.. Nested try running... throw "an error"; Nested catch caught an error } Nested finally is running... catch(e) { Outer print("Nested catch caught " + e); catch caught an error rethrown throw e + " re-thrown"; Outer finally running } finally { print("Nested finally is running..."); }} catch(e) { print("Outer catch caught " + e);} finally { print("Outer finally running");} // Change this for Windows Script Host to say Programming Concepts Compared in Different Languages with Code Examp WScript.Echo(s) http://msdn.microsoft.com/en-us/library/we7h0cz1%28v=vs.80%29.aspx function print(s){ 10/15/2013 document.write(s);}
  54. 54. References: http://msdn.microsoft.com/en-us/library/5kas1c51.aspx 54 10/15/2013

×