Server-Side JScript ObjectsBy Richard Lowe
One particular feature of JScript which makes it attractive is its ability to create its own objects which can
be used in exactly the same syntax that COM objects created with
Server.CreateObject() or VBScript
classes are. VBScript can be retained as the primary scripting language and still take advantage of the
features of JScript objects because objects can be passed to VBScript so that the programmer has the best of
Trim() function, to remove
leading and trailing spaces from a string:
Calling this function is simple; a string is passed to the function and a trimmed string is returned. There's
no need to re-write that function's logic ever again, however it must be included using a server-side
#include in every page it will be called from. (To learn more about regular expressions be sure
to check out the Regular Expression articles on 4Guys!)
Requirements such as the business rules layer of a multi-tiered application may be more complicated than can be comfortably handled in a function. Circumstances may arise where building business logic into ASP is necessary. In these situations JScript objects in ASP can serve as vessels to encapsulate logic or provide placeholders for compiled components. JScript objects are all about breaking complex logic into discreet, manageable chunks for the developer.
Example Company XYZ is moving to an online helpdesk system, where tickets (problems) are called in and must be dealt with. The requirements analysis shows the different ways that problem tickets can be manipulated. They can be created, edited (status changes or notes added), escalated to higher-level support, or closed. There is also a lot of information that goes along with a ticket: which user has reported the problem, the problem description and severity etc.
Working with a ticket might mean writing a lot of code - and many variables (declared on each page) to hold
information temporarily. What if all the operations and data necessary for each ticket could be held in one
place? The remainder of the article shows the creation (and usage in VBScript) of one of the methods that
might be used in a helpdesk
First JScript Object
The process for creating your own custom object in JScript is the same client or server side. First, define the functions you will use as methods. For our example the
Ticket object will have a single function,
createTicket(). This function creates a new ticket by adding a row into a SQL Server
database table. The source code for
createTicket() can be seen at the bottom of this page.
Although the workings of this function are explained with comments, it's important not to be
too concerned with how it works, but instead concentrate on the way it's integrated into the
Ticket object. Take a moment to review the source code below. When you are done, head over to
Part 2, where we'll look at how to encapsulate the
function into an object.