A simple JavaScript class
Function complex (Real, imaginary ){
If (isnan (real) | isnan (imaginary ))
Throw new typeerror ();
This. r = real;
This. I = imaginary;
}
/*
The instance methods of a class are defined as function-valued properties
Of the prototype object. The methods defined here are inherited by all
Instances and provide the shared behavior of the class. Note that JavaScript
Instance methods must use "this" keword to access the instance fields.
*/
Complex. Prototype. Add = function (that ){
Return new complex (this. R + that. R, this. I + that. I );
};
Complex. Prototype. Mul = function (that ){
Return new complex (this. R * That. R-this. I * That. I,
This. R * That. I + this. I * That. R );
};
Complex. Prototype. Mag = function (){
Return math. SQRT (this. R * This. R + this. I * This. I );
};
Complex. Prototype. neg = function () {return new complex (-This. R,-this. I );};
Complex. Prototype. tostring = function () {return "{" + this. R + "," + this. I + "}";};
Complex. Prototype. Equals = function (that ){
Return that! = NULL &&
That. constructor === complex &&
This. r = That. R & this. I = That. I;
};
/*
Class fields (such as constants) and class methods are defined
Properties of the constructor.
Note that class methods do not generally use the "this" Keyword:
They operate only on their arguments.
*/
// Here are some class fields that hold useful predefined complex numbers.
// Their names are uppercase to indicate that they are constants.
// (In ecmascript 5, we cocould actuatlly make these properties read-only .)
Complex. Zero = new complex (0, 0 );
Complex. One = new complex (1, 0 );
Complex. I = new complex (0, 1 );
// This class method parses a string in the format returned by the tostring
// Instance method and returns a complex object or throws a typeerror.
Complex. parse = function (s ){
Try {
VaR M = complex._format.exe C (s); // Regular Expression magic
Return new complex (parsefloat (M [1]), parsefloat (M [2]);
} Catch (x ){
Throw new typeerror ("can't parse '" + S + "' as a complex number .");
}
};
// A "private" class field used in complex. parse () abve.
// The underscore in its name indicates that it is intended for internal use and
// Shocould not be considered part of the public API of this class.
Complex. _ format =/^ \ {([^,] +), ([^}] +) \} $ /;
We can use the code like this:
VaR c = new complex (2, 3 );
VaR d = new complex (C. I, C. R );
C. Add (d). tostring ();
Complex. parse (C. tostring (). Add (C. neg (). Equals (complex. Zero)
Note:
Javescript does not have the keyword "private". This example uses typographical conventions
To provide hints that some properties (whose names are in capital letters) shocould not be changed
And that others (whose names begin with an underscore) shocould not be used outside of the class.
Private properties can be emulated using the local variables of a closure.
Constant properties are possible in ecmascript 5.