November 24, 2014
Hot Topics:

Understanding New JScript .NET Statements

  • January 28, 2002
  • By Essam Ahmed
  • Send Email »
  • More Articles »

JScript .NET is a fully object oriented programming language, since it provides direct support, through the class statement, for creating your own types that encapsulate data, and behavior. This week's article takes an in-depth look at several JScript .NET statements:

  • class
  • const
  • enum
  • package
  • import

Understanding objects and classes

Objects and classes act as placeholders to represent everything from tangible things to immaterial things like ideas and concepts. Objects and classes exist, in part, to manage complexity during the design, implementation, and maintenance phases of a solution's lifecycle. Since objects and classes have the same role, why not just have a class or an object - why two things?

An object is different from a class very subtle but important ways:

  • An object is an instance of a class
  • Objects exist in the context of an active system

An object can be active - acting on its own and having its own thread of execution - or it can be passive - waiting for some other entity to tell it what to do. An object requires system resources, such as memory or disk space, and there can be more than one instance of the same object.

Think of a class as a template for an object. A class is a static (unchanging) representation of a potential object - a class doesn't directly represent an object. When your code creates an instance of an object, what it is really doing is instantiating an object of the type that the class specifies. As soon as the object comes into existence, the class that it is based on is no longer important (unless you want to determine what type the object is or want to change its type).

JScript .NET supports classes through the class keyword.

Understanding the class statement

Consider the following listing:

class kitchenAppliance {
  
  var type : int;

  var weight : int;

  var height: int;
  var width: int;
  var depth: int;

  function kitchenAppliance()
  {
    type = new String("general");
  weight = 0;
  height = 0;
  width = 0;
  depth = 0;
  }
}

The class illustrates a minimal implementation having a constructor and several member variables. Variables that are part of a class, that is, variables that you declare inside of a class are referred to as member variables since they are members (or parts) of the class they reside in. You can access a class's member variables through the class - the member variables typically do not exist unless an instance of the class's object exists (unless you declare a static variable, in which case the variable is accessible without an instance of the class's object).

Member functions, like member variables, are functions that appear within a class declaration and are also accessible through the class's object. There is one type of member function that plays a special role in the class object's lifetime: the constructor. A constructor's role is to (usually) set the initial state of a new object. When you create an instance of a new object, the underlying system calls the object's constructor before any other code can access the object - giving the object the opportunity to initialize itself. Constructors have the same name as their class, as shown in the previous listing. Constructors don't have any limitations on what they can do while they initialize a new object - except that you cannot return a value from a constructor (the return type is implicitly void). A class can have more than one constructor, as I'll demonstrate shortly.

Use a class like you would any other type by declaring a variable that refers to the object and create an instance of it. For example, you could create an instance of a kitchenAppliance and refer to its member variables using the following code:

var stove : kitchenAppliance;
stove = new kitchenAppliance();
// stove now refers to an instance of a 
// kitchenAppliance object
print( stove.type ); // prints: general
print ( stove.weight); // prints: 0

Sometimes it's awkward to create a class and then initialize it, especially if you need to do that throughout your code. A class can have more than one constructor to make it easier to create and initialize a new object. For example, take a look at the following code:

class cubicDimentions {

  function cubicDimentions(theHeight:quantity,
                           theWidth:quantity,
                           theDepth:quantity)
  {
    //...
  }

  function cubicDimentions(height_measure:float,
                           height_units:unit,
                           width_measure:float,
                           width_units:unit,
                           depth_measure:float,
                           depth_units:unit)
  {
    //...
  }
}

myFridge.dimentions = new cubicDimentions(2,new unitMeter(),
                                        1.5,new unitMeter(),
                                        2.5,new unitMeter());

The listing illustrates a cubicDimentions class with two constructors. The first constructor takes three arguments that are quantity types and the second takes six arguments made up of float and unit types. The listing also demonstrates, near the bottom, how the second constructor makes it easier to create an instance of a cubicDimentions object. It is easier to create an cubicDimentions object by using simple float and unit types instead of having to create a new quantity type for each measurement. The JScript .NET compiler determines which constructor your code refers to based on the types of the parameters you pass to it.

Understanding Static class members

The static modifier allows you to create member variables and functions that you can directly refer to without an instance of the class object. Static members are useful in cases where a class acts as a helper - operating on other objects to perform some operation. For example, the kitchen appliances sample code includes a class called converter that converts from one unit of measure to another, as shown in the following listing:

class converter
{
  static function convert(fromQty : quantity , 
                          toQty : quantity) : quantity
  {
    var ratio : float;
    var newQty : quantity;
    ratio = toQty.units.conversionRatio( fromQty.units );
    if( ratio == -1 ) // -1 indicates that the conversion
                      //    is not possible
      newQty = new quantity( -1 , new unit() );  
    else
      newQty = new quantity( (ratio*fromQty.amount) , 
                             toQty.units );
    return newQty;
  }
}

The class has a single static member function that converts from one quantity (a type that represents an numeric measure and a unit of measurement) to another quantity based on their respective, underlying units of measure (units). The convert member function operates on existing objects and does not need to maintain any of its own data internally, making it a good candidate for being static. When a member function is static, you can simply refer to it directly, as shown:

var demoQty : quantity;
demoQty = converter.convert( 
  myFridge.weight , 
  new quantity( 0 , new unitKg() ) );

The listing calls the convert method directly through the converter class without having an instance of the class object on hand. You can refer to static member variables in the same way.

Understanding the const statement

The const statement allows you to declare a variable that has an unchanging value. const variables are useful when you use a value throughout your code and work to make it easier to maintain and understand your code. For example, you could use a constant variable to specify the conversion ratio between miles and kilometers, as shown in the following listing:

const milesTOkilometers : float = 1.6;
distanceToWork = commuteDistance * milesTOkilometers;

If you find that you need a more accurate measure, in kilometers, you can simply change the value of the constant variable without having to change all the code that uses it, as shown:

// use a more accurate conversion ratio...
const milesTOkilometers : float = 1.609344;
distanceToWork = commuteDistance * milesTOkilometers;

Understanding the enum statement

The enum statement allows you to create symbolic names that are abound to a particular type. For example, consider the following code:

enum appliances : int {
  fridge,
  stove,
  dishwasher,
  none
}

class kitchenAppliance {
  
  var type : appliances;
  //...

  function kitchenAppliance()
  {
    type = appliances.none;
    // ...
  }
}

The listing shows an enumeration called appliances defining several types, bound to an integer type. The kitchenAppliance declares a type variable, that represents the type of kitchen appliance, that's bound to the appliances enumeration. Using this technique allows the compiler to confirm, at compile time, that the value you assign to the type variable is valid and makes your code easier to read.

Understanding the package statement

A package allows you do create logical groupings of your code - the groups are formally referred to as namespaces. A package is useful in cases where there are name collisions between your code and some other class or third party library. For example, the following listing groups two classes into a package (or namespaces) to avoid name collisions with existing classes from other libraries:

package d2sStandardLib {

  class convert {
    //...
  }

  class kitchenAppliance {
    //...
  }
}

var stdLib : d2sStandardLib.kitchenAppliance;
stdLib = new d2sStandardLib. kitchenAppliance();

Understanding the import statement

The import statement makes members of other namespaces (or packages) available for you to use in your code. The import statement allows the JScript .NET compiler to resolve references to other namespaces and allows the Common Language Runtime to ensure that libraries that your applications rely on are available before your code executes. The following listing demonstrates how to use the import statement to gain access to the the System.Data and System.Text namespaces:

import System.Data;
import System.Text;

Summary

This article introduced and explained some of the newer statements available in JScript .NET, their benefits, and how to use them. The next three upcoming articles in this series look at applying JScript .NET and the .NET Framework to practical applications in the form of ASP.NET sites, Web Services, and Windows Forms applications.


Essam Ahmed is the author of "JScript .NET Programming" (ISBN 0764548689, Published by Hungry Minds September 2001), many articles (including some at CodeGuru.com) and book reviews (also available at CodeGuru.com). Contact Essam at essam@designs2solutions.com, or at his Web site

# # #






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel