Share via


Creating Your Own Classes

The class statement defines classes. By default, class members are publicly accessible, which means that any code that can access the class can also access the class member. For more information, see JScript Modifiers.

Classes with Fields

Fields define the data used by an object and are similar to the properties in a prototype-based object. Here is an example of a simple class that has two fields. An instance of the class is created with the new operator:

class myClass {
   const answer : int = 42; // Constant field.
   var distance : double;   // Variable field.
}

var c : myClass = new myClass;
c.distance = 5.2;
print("The answer is " + c.answer);
print("The distance is " + c.distance);

The output of this program is:

The answer is 42
The distance is 5.2

Classes with Methods

Classes can also contain methods, which are functions contained in the class. Methods define the functionality to manipulate the data of an object. The class myClass defined above can be redefined to include a method.

class myClass {
   const answer : int = 42;         // Constant field.
   var distance : double;           // Variable field.
   function sayHello() :String {    // Method.
      return "Hello";
   }
}

var c : myClass = new myClass;
c.distance = 5.2;
print(c.sayHello() + ", the answer is " + c.answer); 

The output of this program is:

Hello, the answer is 42

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. In this example, a constructor is added to the myClass class.

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);

The output of this program is:

The distance is 8.5

See Also

Concepts

Advanced Class Creation

Other Resources

Class-based Objects

JScript Objects