• Like
Jscript part2
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Jscript part2



Published in Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads


Total Views
On SlideShare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


  • 1. Girish Srivastava girish092.ch@gmail.com 1 10/15/2013
  • 2. OOPs Concept  Object-oriented programming (OOP) is a programming language model organized around "objects" rather than "actions" and data rather than logic.  The concepts and rules used in object-oriented programming provide these important benefits:  The concept of a data class makes it possible to define subclasses 2 of data objects that share some or all of the main class characteristics. Called inheritance.  Since a class defines only the data it needs to be concerned with, when an instance of that class (an object) is run, the code will not be able to accidentally access other program data. This characteristic of data hiding provides greater system security and avoids unintended data corruption.  The definition of a class is reuseable not only by the program for which it is initially created but also by other object-oriented programs. 10/15/2013  The concept of data classes allows a programmer to create any new
  • 3. Object-Oriented Programming Concepts  Objects collect related data items in a single place and     3 make it simpler, or at least more logical, to access those items. JScript refers to the items collected within an object as its properties. JScript objects not only store data, they also store functions. The relationship between an object and an instance of an object is the same as the relationship between a data type and a variable of that data type. In a typeless language such as JScript, this distinction is blurred but is still present. 10/15/2013
  • 4. Introduction to Classes  To create a class, use the class keyword followed by a name for the object.  The name of a class follows the rules we have applied so far for variable and function names.  As a name that represents a group of items, a class has a body that would be used to define the items that compose it. • class Book{ • var Title : String; • var Author : String; • var Pages : int; • var CoverType : char; • } 4 10/15/2013 The items that compose a class are called members of the
  • 5. Declaring a Class  Unlike regular data types, a variable of a class must be explicitly allocated a memory space, big enough to contain its data. This is done using the new operator. Here is an example: class Book { var Title : String; var Author : String; var Pages : int; var CoverType : char; } var BrandNew : Book = new Book; var BrandNew : Book; BrandNew = new Book;  You can also allocate memory when declaring the variable, that is, on the same line. 5 10/15/2013
  • 6. Class Variable Initialization  initialize a class, you can access each member and assign it an appropriate value. 6 class Book { var Title : String; var Author : String; var Pages : int; var CoverType : char; } var BrandNew : Book; BrandNew = new Book; BrandNew.Title = "Webber Databases With JScript .NET"; BrandNew.Author = "Catherine Mamfourh"; BrandNew.Pages = 1225; BrandNew.CoverType = 'H'; print("Book Characteristics"); print("Title: ", BrandNew.Title); print("Author: ", BrandNew.Author); print("Pages: ", BrandNew.Pages); print("Cover: ", BrandNew.CoverType); 10/15/2013
  • 7. Creating Member Functions  To create a member function of a class, type the function keyword followed by a name, the necessary parentheses, and the curly brackets that delimit the body of a function. class FRectangle { var Length : double; var Height : double; function Perimeter() { } } 7 10/15/2013
  • 8. Example 8 class FRectangle { var Length : double; var Height : double; function Perimeter() : double { return (Length + Height) * 2; } function Area() : double { return Length * Height; } function ShowCharacteristics() { print("Rectangle Characteristics"); print("Length: ", Length); print("Height: ", Height); print("Perimeter: ", Perimeter()); print("Area: ", Area()); } } var Recto : FRectangle = new FRectangle; Recto.Length = 24.55; Recto.Height = 20.75; Recto.ShowCharacteristics(); 10/15/2013
  • 9. Class-based Objects  Since JScript is a class-based, object-oriented programming language, it is possible to define classes that can inherit from other classes.  Defined classes can have methods, fields, properties, and subclasses. Inheritance enables classes to build on existing classes and override selected base-class methods and properties.  Creating Your Own Classes  The class statement defines classes. By default, class Visibility are publicly accessible, which means that any Valid for membersModifier class, class member, interface, code that can access the class can also access the public interface member, or enumerations class member. private protected 9 class member class member internal 10/15/2013 class, class member, enumeration
  • 10. Classes with Constructors  You can define a constructor for a class. A constructor, which is a method with the same name as the class, is run when a class is created with the new operator. You may not specify a return type for a constructor. 10 class myClass { const answer : int = 42; // Constant field. var distance : double; // Variable field. function sayHello() :String { // Method. return "Hello"; } // This is the constructor. function myClass(distance : double) { this.distance = distance; } } var c : myClass = new myClass(8.5); print("The distance is " + c.distance); 10/15/2013
  • 11. Advanced Class Creation  When you define a JScript class, you can assign properties, and the defined class can subsequently inherit from other classes.  Classes with Properties  JScript uses function get and function set statements to 11 specify properties. You can specify either or both accessors to create read-only, write-only, or read-write properties, although write-only properties are rare and may indicate a problem with the design of the class.  The calling program accesses properties in the same way that it accesses fields. The main difference is that the getter and setter for the property are used to perform the access, whereas fields are accessed directly.  Properties are usually used to access private or protected fields of the class. 10/15/2013
  • 12.  In this example, properties are used to access a protected field. The field is protected to help prevent outside code from changing its value while allowing derived classes to access it. class Person { // The name of a person. // It is protected so derived classes can access it. protected var name : String; // Define a getter for the property. function get Name() : String { return this.name; } // Define a setter for the property which makes sure that // a blank name is never stored in the name field. function set Name(newName : String) { if (newName == "") throw "You can't have a blank name!"; this.name = newName; } function sayHello() { return this.name + " says 'Hello!'"; } } // Create an object and store the name Fred. var fred : Person = new Person(); fred.Name = "Fred"; print(fred.sayHello()); 12 10/15/2013
  • 13. Inheritance from Classes  The extends keyword is used when defining a class that builds on another class.  JScript can extend most common-language specification (CLS)-compliant classes.  A class defined using the extends keyword is called a derived class, and the class that is extended is called the base class. class Student extends Person { // Override a base-class method. function sayHello() { return this.name + " is studying for finals."; } } var mary : Person = new Student; mary.Name = "Mary"; print(mary.sayHello()); 13 10/15/2013
  • 14. Example class BaseCls { function get Z() : int { return 100 ;} } class DervCls extends BaseCls { hide function get Z() : String { return "*" ;} } class UseClasses { var BObj : BaseCls = new DervCls(); var DObj : DervCls = new DervCls(); function ShowZ() { print("Accessed through base class: " + BObj.Z); print("Accessed through derived class: " + DObj.Z); } 14 } 10/15/2013
  • 15. Example of Method Overloading 15 var methodOverload = new MethodOverload(); methodOverload.Greetings(); methodOverload.Greetings("Mr. Brown"); methodOverload.Greetings(97, "Mr. Brown"); class MethodOverload { function Greetings() { print("Hello, and welcome!"); } function Greetings(name : String) { print("Hello, " + name + "!"); } function Greetings(ticket : int, name : String) { print("Hello, " + name + "! Your ticket number is " + ticket + "."); } } 10/15/2013
  • 16. Prototype-based Objects  Since JScript is an object-oriented programming language, it supports the definition of custom constructor functions and inheritance.  Constructor functions (also called constructors) provide the ability to design and implement your own prototypebased objects.  Inheritance allows prototype-based objects to share a common set of properties and methods that can be dynamically added or removed.  Creating Your Own Objects with Constructor Functions  A powerful feature of JScript is the ability to define 16 constructor functions to create custom prototype-based objects for use in your scripts.  To create an instance of a prototype-based object, you first 10/15/2013 must define a constructor function. This process creates a
  • 17. Constructors with Properties  The following example defines a constructor function for pasta objects. The this statement allows the constructor to initialize the object. • • • • // pasta is a constructor that takes four parameters. function pasta(grain, width, shape, hasEgg) { this.grain = grain; // What grain is it made of? this.width = width; // How many centimeters wide is it? • this.shape = shape; // What is the cross-section? • this.hasEgg = hasEgg; // Does it have egg yolk as a binder? • }  After defining an object constructor, you create 17 instances of the object with the new operator. Here the pasta constructor is used to create spaghetti and linguine objects. 10/15/2013  var spaghetti = new pasta("wheat", 0.2, "circle", true);
  • 18. Advanced Object Creation  JScript supports inheritance with custom prototype- based objects. Through inheritance, prototype-based objects can share a common set of properties and methods that can be dynamically added or removed. Moreover, individual objects can override the default behavior.  Creating a Prototype-based Object  To create an instance of a prototype-based object, you first must 18 define a constructor function.  Once this constructor is written, you can use properties of the prototype object to create inherited properties and shared methods. The constructor provides the instance-specific information to an object, while the prototype object provides the object-specific information and methods to the object.  The this statement enables the method to access members of the object. 10/15/2013
  • 19. Cont… // Define the constructor and add instance specific information. function Circle (radius) { this.r = radius; // The radius of the circle. } // Add a property the Circle prototype. Circle.prototype.pi = Math.PI; function ACirclesArea () { // The formula for the area of a circle is pi*r^2. return this.pi * this.r * this.r; } // Add a method the Circle prototype. Circle.prototype.area = ACirclesArea; // This is how you would invoke the area function on a Circle object. var ACircle = new Circle(2); var a = ACircle.area(); Using this principle, you can define additional properties for existing constructor functions 19 10/15/2013
  • 20. Jscript Object  Intrinsic Objects  JScript provides 16 intrinsic objects as part of the language specification.  Some of the commonly used objects are:  JScript Array Object  JScript Date Object  JScript Math Object  JScript Number Object  JScript Object Object  JScript String Object 20 10/15/2013
  • 21. JScript Array Object  An Array object is a variable that groups related pieces of data.  A unique number, called an index or subscript, references each piece of data in the array. To access the data stored in the array, the array identifier and the index are combined with the index operator "[]", for example, theMonths[0].  Creating an Array  To create a new array, use the new operator and the Array 21 constructor. In this example, the array constructor is used to theMonths[6] = "Jul"; construct an array with length 12. Then, data is entered into the theMonths[7] = "Aug"; array. theMonths[8] = "Sep";  var theMonths = new Array(12);  theMonths[0] = "Jan"; theMonths[9] = "Oct";  theMonths[1] = "Feb"; theMonths[10] = "Nov"; theMonths[11] = "Dec";  theMonths[2] = "Mar";  theMonths[3] = "Apr"; 10/15/2013  theMonths[4] = "May";
  • 22. Cont…  When you create an array using the Array keyword, JScript includes a length property, which records the number of entries.  If you do not specify a number, the length is set to zero, and the array has no entries.  If you specify a number, the length is set to that number. If you specify more than one parameter, the parameters are used as entries in the array.  In addition, the number of parameters is assigned to the length property, as in the following example, which is equivalent to the preceding example.  var theMonths = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); 22 10/15/2013
  • 23. Cont…  Using Expando Properties of Arrays  Array objects, just as any other object based on the JScript Object object, support expando properties.  Expando properties are new properties that you dynamically add and delete from an array, like array indices.  In addition, adding or deleting expando properties does not change the length property.  For Example: • // Initialize an array with three elements. • var myArray = new Array("Hello", 42, new Date(2000,1,1)); print(myArray.length); // Prints 3. • // Add some expando properties. They will not change the length. myArray.expando = "JScript"; • myArray["another Expando"] = "Windows"; • print(myArray.length); // Still prints 3. 23 Typed Arrays var theMonths : String[] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug 10/15/2013 "Sep", "Oct", "Nov", "Dec"];
  • 24. Using Typed Arrays  A data type that is followed by a set of square brackets defines a one-dimensional typed array. To define an ndimensional array, the base data type is followed by a set of square brackets with n-1 commas between the brackets.  The following shows some simple array declarations:  // Simple array of strings; initially empty. The variable 'names' itself  // will be null until something is assigned to it  var names : String[];  // Create an array of 50 objects; the variable 'things' won't be null,  // but each element of the array will be until they are assigned 24 values.  var things : Object[] = new Object[50]; // Put the current date and time in 10/15/2013 element 42.
  • 25. Cont…  // An array of arrays of integers; initially it is null.  var matrix : int[][]; // Initialize the array of arrays.  matrix = new (int[])[5]; // Initialize each array in the array of arrays.  for(var i = 0; i<5; i++)  matrix[i] = new int[5]; // Put some values into the matrix.  matrix[2][3] = 6;  matrix[2][4] = 7;  // A three-dimensional array var multidim :  double[,,] = new double[5,4,3]; // Put some values into the matrix. multidim[1,3,0] = Math.PI*5.;  For More details:  http://msdn.microsoft.com/en-us/library/9f2a8x5w(v=vs.80).aspx 25 10/15/2013
  • 26. JScript Date Object  The JScript Date object can be used to represent     26 arbitrary dates and times, to get the current system date, and to calculate differences between dates. It has several predefined properties and methods. The Date object stores a day of the week; a month, day, and year; and a time in hours, minutes, seconds, and milliseconds. This information is based on the number of milliseconds since January 1, 1970, 00:00:00.000 Coordinated Universal Time (UTC), formerly known as Greenwich Mean Time. JScript can handle dates that are in the approximate range from 250,000 B.C. to 255,000 A.D., although 10/15/2013 some formatting functionality is supported only for dates
  • 27. Creating a Date Object  To create a new Date object, use the new operator. var s : String = "Today's date is: "; // Declare variables. var d : Date = new Date(); // Create Date object with today's date. s += (d.getMonth() + 1) + "/"; // Get month s += d.getDate() + "/"; // Get day s += d.getYear(); // Get year. print(s); // Print date. There are many more predefined method are present, please check from following url: http://msdn.microsoft.com/en-us/library/xby9ffhf(v=vs.80).aspx 27 10/15/2013
  • 28. JScript Math Object  The Math object has a number of intrinsic properties and methods. The properties are specific numbers.  Using the Math Object  One of these specific numbers is the value of pi (approximately 3.14159...). This is the value of the Math.PI property, which is used in the following example.  // A radius variable is declared and assigned a numeric value.  var radius = 4;  var area = Math.PI * radius * radius;  // Note capitalization of Math and PI.  One built-in method of the Math object is the exponentiation method, or pow, which raises a number to a specified power. The following example uses both pi and exponentiation.  // This formula calculates the volume of a sphere with the given radius.  var volume = (4/3)*(Math.PI*Math.pow(radius,3)); 28 10/15/2013
  • 29. JScript Number Object  The primary purpose of the Number object is to collect properties and methods that are used for the default numeric data type, the Number data type.  The numeric constants provided by the properties of the Number object are listed in the table below. Property Description MAX_VALUE Largest possible number, about 1.79E+308; can be positive or negative. (Value varies slightly from system to system.) MIN_VALUE Smallest possible number, about 2.22E-308; can be positive or negative. (Value varies slightly from system to system.) NaN Special nonnumeric value, "not a number." POSITIVE_INFINITY Any positive value larger than the largest positive number (Number.MAX_VALUE) is automatically converted to this value; represented as infinity. 29 NEGATIVE_INFINITY 10/15/2013 Any value more negative than the largest negative number (-Number.MAX_VALUE) is automatically
  • 30. Cont…  Number.NaN is a special property that is defined as     30 not a number. Number.NaN is returned when an expression that cannot be represented as a number is used in a numeric context. For example, NaN is returned when either the string "Hello" or 0/0 (zero divided by zero) is used as a number. NaN compares as unequal to any number and to itself. To test for a NaN result, do not compare against Number.NaN; use the isNaN method of the Global object instead. 10/15/2013
  • 31. JScript Object Object  All objects in JScript based on the Object object support expando properties, or properties that can be added and removed while the program is running.  Using the Object Object  These properties can have any name, including numbers. A name of a property that is a simple identifier can be written after a period that follows the object name, such as: • var myObj = new Object(); • // Add two expando properties, 'name' and 'age' • myObj.name = "Fred"; • myObj.age = 53;  You can also access an object's properties using the index operator, [].  This is required if the name of the property is not a simple identifier, or if the name of the property is not known when you write the script. 31 • var myObj = new Object(); • // This identifier contains spaces. • myObj["not a simple identifier"] = "This is the property value"; 10/15/2013 • // This identifier is a number. • myObj[100] = "100";
  • 32. Cont…  Although the index operator is more commonly associated with accessing array elements, the index is always the property name expressed as a string literal when used with objects.  Array objects have a special length property that changes when new elements are added; in general, objects do not have a length propertyname iswhen the indexthat the property The property even treated Meaning operator is used Operator as name to add properties. Period (.) An identifier Cannot be manipulated as  Notice the important difference between the two ways of data accessing object properties. Index ([]) A string literal Can be manipulated as data  This difference becomes useful when you do not know the 32 property names until runtime (for example, when you are constructing objects based on user input). To extract 10/15/2013 all the properties from an associative array, you must use the for ...
  • 33. JScript String Object  A String object in JScript represents textual data such as words and sentences.  String objects are rarely created explicitly with the new operator because they are usually created implicitly by assigning a string literal to a variable.  Using the String Object  The String object has many built-in methods. One of these is the substring method, which returns part of the string.  It takes two numbers as its arguments. The first number is the zerobased index that indicates the beginning of the substring, and the second number indicates the end of the substring. • var aString : String = "0123456789"; • var aChunk : String = aString.substring(4, 7); // Sets aChunk to "456".  The String object also has a length property. This property contains the number of characters in the string (0 for an empty string). This a numeric value and can be used directly in calculations. This example obtains the 10/15/2013 33 length of a string literal.  var howLong : int = "Hello World".length // Sets the howLong variable to
  • 34. Examples o o o o o var primStr : Object = "This is a string"; print(primStr.length); // Read the length property. print(primStr.toUpperCase()); // Call a method. primStr.myProperty = 42; // Set a new property. print(primStr.myProperty); // Try to read it back. For String objects created with the new statement, custom properties can be set: var newStr : Object = new String("This is also a string"); print(newStr.length); // Read the length property. print(newStr.toUpperCase()); // Call a method. newStr.myProperty = 42; // Set a new property. print(newStr.myProperty); // Try to read it back. 34 10/15/2013
  • 35. arguments Object  An object representing the currently executing function,     35 its arguments, and the function that called it. This object cannot be constructed explicitly. The arguments object has no methods. An arguments object is instantiated for each function when it begins execution. The arguments object is directly accessible only within the scope of its associated function. All parameters passed to a function and the number of parameters are stored in the arguments object. The arguments object is not an array, but the individual arguments are accessed using [ ] notation, the same way array elements are accessed. 10/15/2013
  • 36. Example 36 function argTest(a, b) : String { var i : int; var arguments; var s : String = "The argTest function expected "; var numargs : int = arguments.length; // Get number of arguments passed. var expargs : int = argTest.length; // Get number of arguments expected. if (expargs < 2) The arguments object is not s += expargs + " argument. "; available when running in fast else mode, the default for JScript. To s += expargs + " arguments. "; compile a program from the if (numargs < 2) command line that uses s += numargs + " was passed."; the arguments object, you must else turn off the fast option by s += numargs + " were passed."; using /fast-. It is not safe to turn off s += "n" The output: for (i =0 ; i < numargs; i++){ // Get argument the fast option in ASP.NET because contents. The argTest function expected 2 s += " Arg " + i + " = " + arguments[i] + "n"; of threading issues. arguments. 1 was passed. Arg 0 } = return(s); // Return list of arguments. 42 The argTest function expected 2 arguments. 3 were } passed. Arg 0 = Tue Sep 7 print(argTest(42)); print(argTest(new Date(1999,8,7),"Sam",Math.PI)); 00:00:00 PDT 1999 10/15/2013 Arg 1 = Sam
  • 37. Boolean Object  The Boolean object references a Boolean value.  function Boolean( [boolValue : boolean] )  “boolValue” is Optional. The initial Boolean value for the new object. If boolValue is omitted, or is false, 0, null, NaN, or an empty string, the initial value of the Boolean object is false. Otherwise, the initial value is true.  The Boolean object is a wrapper for Boolean data. The primary purposes for the Boolean object are to collect its properties into one object and to allow Boolean values to be converted into strings via the toString method. The Boolean object is similar to the boolean data type. 37 10/15/2013
  • 38. Enumerator Object  Enables enumeration of items in a collection.  varName = new Enumerator([collection])  “varName” is Required. The variable name to which the enumerator is assigned.  “Collection” is Optional. Any object that implements the IEnumerable interface, such as an array or collection.  Every collection is automatically enumerable in JScript. Consequently, you do not need to use the Enumerator object to access members of a collection. You can access any member directly using the for...in statement. The Enumerator object is provided for backwards compatibility.  The Enumerator object, which provides a way to access any member of a collection, behaves in a manner similar to the For...Each statement in VBScript.  You can create a collection in JScript by defining a class that 10/15/2013 38 implements IEnumerable. Collections can also be created
  • 39. Example  The following code uses the Enumerator object to print the letters of the available drives and their names (if available): 39 // Declare variables. var n, x; var fso : ActiveXObject = new ActiveXObject("Scripting.FileSystemObject"); // Create Enumerator on Drives. var e : Enumerator = new Enumerator(fso.Drives); for (;!e.atEnd();e.moveNext()) { // Loop over the drives collection. x = e.item(); if (x.DriveType == 3) // See if network drive. n = x.ShareName; // Get share name else if (x.IsReady) // See if drive is ready. n = x.VolumeName; // Get volume name. 10/15/2013 else n = "[Drive not ready]";
  • 40. ActiveXObject Object  An object that provides an interface to an Automation object. function ActiveXObject(ProgID : String [, location : String])  “ProgID” Required. A string of the form "serverName.typeName", where serverName is the name of the application providing the object, and typeName is the name of the type or class of the object to create.  “Location” Optional. The name of the network server where the object is to be created.   Typically, an automation server provides at least one type of object. For example, a word-processing application may provide an application object, a document object, and a toolbar object.  The following code starts an application (in this case, a Microsoft Excel worksheet) by calling the ActiveXObject object constructor. The ActiveXObject allows you to refer to the application in your code. Using the following example, 10/15/2013 40 you can access properties and methods of the new object
  • 41. Example // Declare the variables var Excel, Book; // Create the Excel application object. Excel = new ActiveXObject("Excel.Application"); // Make Excel visible. Excel.Visible = true; // Create a new work book. Book = Excel.Workbooks.Add() // Place some text in the first cell of the sheet. Book.ActiveSheet.Cells(1,1).Value = "This is column A, row 1"; // Save the sheet. Book.SaveAs("C:TEST.XLS"); // Close Excel with the Quit method on the Application object. Excel.Application.Quit(); http://msdn.microsoft.com/en-us/library/6958xykx.aspx 41 10/15/2013
  • 42. Error Object  Contains information about errors. There are two forms of the Error constructor. o function Error([description : String ]) o function Error([number : Number [, description : String ]]) o “number” Optional. Numeric value assigned to the error, specifying the value of the number property. Zero if omitted. o “description” Optional. Brief string that describes the error, specifying the initial value of the description and message properties. Empty string if omitted.  Error objects can be explicitly created using the constructor shown above. You can add properties to the Error object to expand its capabilities. An Error object is also created whenever a run-time error occurs to describe the error.  Typically, an Error object is thrown with the throw statement and the expectation that it will be caught by a try...catch statement. You can use a throw statement to pass any type of data as an error; the throw statement will not implicitly create an Error object. However, by throwing an Error object, a catch block can treat JScript run-time errors and user-defined errors similarly. 10/15/2013 42
  • 43. Example 43 try { print("Outer try is example  The following running"); illustrates a use of the try try { { print("Nested try is running"); // Throw an error. throw new Error(301, "an error"); }catch(e) throw new Error(42,"No question"); { } catch(e) print("Nested catch caught " + e.message); { throw e; print(e) } // Extract the error code from the error number. finally print(e.number & 0xFFFF) { print("Nested finally is running"); print(e.description) } } } catch(e) { print("Outer catch caught " + e.message); } finally { print("Outer finally is running"); } Error object. 10/15/2013
  • 44. 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.  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.  Some of the methods are: 44 o escape Method (Returns an encoded String object that can be read on all computers.) o eval Method (Evaluates JScript code and executes it. ) o isFinite Method (Returns a Boolean value that indicates if a supplied number is finite.) o isNaN Method (Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). ) o parseFloat Method (Returns a floating-point number converted from a string. ) 10/15/2013 o parseInt Method (Returns an integer converted from a string.)
  • 45. RegExp Object  An intrinsic global object that stores information about the results of regular expression pattern matches. This object cannot be constructed explicitly.  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  45 re = new RegExp("pattern",["flags"]) o re Required. The variable name to which the regular expression pattern is assigned. o 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. o flags Optional. Enclose flag in quotation marks if you use Syntax 2. Available flags, which may be combined, are: 10/15/2013 o · g (global search for all occurrences of pattern) o · i (ignore case)
  • 46. Example: var s : String = "The rain in Spain falls mainly in the plain"; // Create regular expression object using Syntax 1. var re1 : RegExp = new RegExp("Spain","i"); // Create regular expression object using Syntax 2. var re2 : RegExp = /IN/i; // Find a match within string s. print(s.match(re1)); print(s.match(re2)); 46 10/15/2013
  • 47. Regular Expression Syntax A regular expression is a pattern of text that consists of ordinary characters (for example, letters a through z) and special characters, known as metacharacters. The pattern describes one or more strings to match when searching text. Expression Matches /^s*$/ Match a blank line. /d{2}-d{5}/ Validate an ID number consisting of 2 digits, a hyphen, and an additional 5 digits. /<s*(S+)(s[^>]*)?>[sS]*<s*/1s*>/ Match an HTML tag. 47 http://msdn.microsoft.com/enus/library/ae5bf541(v=vs.80).aspx 10/15/2013
  • 48. Regular Expression Programming  You can use regular expressions in JScript to search for patterns in a string, replace text, and extract substrings.  Searching 48 Exec method var src = "The quick brown fox jumps over the lazy dog."; // Create regular expression pattern with a global flag. var re = /w+/g; // Get the next word, starting at the position of lastindex. var arr; while ((arr = re.exec(src)) != null) { print (arr.index + "-" + arr.lastIndex + " " + 10/15/2013 arr[0]);
  • 49. Explanation  The previous JScript example finds all occurrences of a      49 word. The statement that creates the regular expression is var re = /w+/g; The /w+/ pattern specifies to match one or more of any of the following characters: A-Z, a-z, 0-9, and the underscore character. The g (global) flag that follows the pattern specifies that the search should find all occurrences of the pattern instead of just the first occurrence. You can also use the following alternative JScript syntax. var re = new RegExp("w+", "g");  To retrieve each match, the exec Method keeps 10/15/2013
  • 50. Data  The way that JScript copies, passes, and compares data depends on how the data is stored, which in turn depends on the type of the data.  JScript stores data either by value or by reference.  By Value vs. By Reference  JScript copies, passes, and compares numbers and Boolean values (true and false) by value.  This process allocates a space in computer memory and copies the value of the original into it.  Changes to the original do not affect the copy (and vice versa) because the two are separate entities. Two numbers or Boolean values are considered equal if they have the same value. 50 10/15/2013
  • 51. Cont…  JScript copies, passes, and compares objects, arrays, and functions by reference.  This process essentially creates a reference to the original item and uses the reference as if it were a copy.  Changes in any one, change both the original and the copy (and vice versa). There is really only one entity; the copy is just another reference to the data.  Function Parameters  When JScript passes a parameter to a function by value, it makes a separate copy of that parameter that exists only inside the function.  Even though objects and arrays are passed by reference, if a new value in the function directly overwrites them, the new value is not reflected outside the function.  Only changes to properties of objects, or elements of arrays, are visible outside the function. 51 10/15/2013
  • 52. Example • function clobber(param) { • // Overwrite the parameter; this will not be seen in the calling code • param = new Object(); • param.message = "This will not work."; • } • function update(param) { • // Modify the property of the object; this will be seen in the calling code. • param.message = "I was changed."; • } • // Create an object, and give it a property. • var obj = new Object(); • obj.message = "This is the original."; • // Call clobber, and print obj.message. • clobber(obj); • print(obj.message); • // Call update, and print obj.message. • update(obj); • print(obj.message); 52 10/15/2013 • The first function overwrites the input parameter, which prevents further the changes to the parameter from affecting the original input argument.
  • 53. Conditional Compilation  Conditional compilation enables JScript to use new language features without sacrificing compatibility with older versions that do not support the features. Some typical uses for conditional compilation include using new features in JScript, embedding debugging support into a script, and tracing code execution.  http://msdn.microsoft.com/enUS/library/ahx1z4fs(v=vs.80).aspx 53 10/15/2013
  • 54. Debugging in server side  The Microsoft Script Debugger is a powerful debugging     54 tool that can help you quickly locate bugs and interactively test your server-side scripts. You can do the following things using the features of Microsoft Script Debugger: Run your server-side scripts one line at a time. Open a command window to monitor the value of variables, properties, or array elements, during the execution of your server-side scripts. Set pauses to suspend execution of your server-side scripts (using either the debugger or a script command) at a particular line of script. Trace procedures while running your server-side script. 10/15/2013
  • 55. Debugging  To add breakpoints to your server-side scripts written in JScript, insert a debugger statement before a suspect line of script. For example, the following script includes adebugger statement that interrupts execution and automatically starts Script Debugger each time the script loops through a new value. o o o o o <%@ Language= "JScript" %> <% for (var count = 1; count <= 10; count++) { var eventest = count%2 //Set breakpoint so that user can step through execution of script. o debugger o if (eventest == 0) o Response.Write("Even value is " + count + "<br>") } %> 10/15/2013 55 o http://msdn.microsoft.com/en-
  • 56.  Resources:  http://msdn.microsoft.com/en- US/library/9kzd4syw(v=vs.80).aspx  http://msdn.microsoft.com/enUS/library/bsz6d1zs(v=vs.80).aspx 56 10/15/2013