Develop > Programming > Introduction to JavaScript in Service Manager > Using JavaScript in Service Manager > Accessing a JavaScript class definition from another JavaScript

Accessing a JavaScript class definition from another JavaScript

Suppose you have two different JavaScript libraries and you do not want to copy the code from one library to the other just to make a JavaScript class definition available to the other one. For example, you define a MyClass class in Test2, then you instantiate MyClass in Test3, and then you call a function in Test4 passing the instantiated object in Test3 to that function; additionally, you may want the function in Test4 to be able to check if the received object is actually an instantiation of the class defined in Test2. You then need to make Test3 to recognize MyClass.

To achieve this behavior, in the Test2 file, you can add a function that returns the class itself, instead of an instantiated object of the class. If you call this function from Test4, you get a pointer to the class definition.

See the following for the sample scripts.

Test2

var MyClass = function () {
    this.var1 = 'variable 1';
    this.var2 = 'variable 2';
};

MyClass.prototype.getVariable1 = function() {
    return this.var1;
};

MyClass.prototype.getVariable2 = function() {
    return this.var2;
};

function require() {
    return MyClass;
};

Test3

var MyClass = lib.Test2.require();

var objMyClass = new MyClass();

print('Test3>', objMyClass instanceof lib.Test2.require());

lib.Test4.checkit(objMyClass);

Test4

var MyClass = lib.Test2.require();

function checkit( anObject ) {
    print('Test4>', anObject instanceof MyClass);
    print( anObject.getVariable1() );
    print( anObject.getVariable2() );
    print( anObject.var1 );
    print( anObject.var2 );
};