Click here to load reader

Jscript part2

Embed Size (px)

Citation preview

2. OOPs Concept Object-oriented programming (OOP) is a programminglanguage 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 subclasses2of 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 3make 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 aname 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; } 410/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 beexplicitly 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 thevariable, that is, on the same line. 510/15/2013 6. Class Variable Initialization initialize a class, you can access each member and assign it anappropriate value.6class 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 thefunction 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() { } } 710/15/2013 8. Example8class 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-orientedprogramming 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. privateprotected 9class member class memberinternal10/15/2013 class, class member, enumeration 10. Classes with Constructors You can define a constructor for a class. A constructor, whichis 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.10class 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 assignproperties, and the defined class can subsequently inherit from other classes. Classes with Properties JScript uses function get and function set statements to11specify 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 protectedto 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()); 1210/15/2013 13. Inheritance from Classes The extends keyword is used when defining a classthat 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()); 1310/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 Overloading15var 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 programminglanguage, 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 define16constructor 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 forpasta 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 create17instances 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 must18define 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 1910/15/2013 20. Jscript Object Intrinsic Objects JScript provides 16 intrinsic objects as part of thelanguage 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 Object2010/15/2013 21. JScript Array Object An Array object is a variable that groups related piecesof 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 Array21constructor. 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"); 2210/15/2013 23. Cont Using Expando Properties of Arrays Array objects, just as any other object based on the JScript Objectobject, 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. 23Typed 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 bracketsdefines 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 assigned24values. 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