Saturday, December 4, 2010

Object ASP

Object ASP

I often hear other programmers saying classic ASP isn't object oriented. This is a mistake. ASP requires you to use a scripting language and both vbscript and javascript which a the languages of choice under ASP are oop enabled.

The problem I think is that for most purposes, ASP is a quick and dirty solution to getting a website up and running that doesn't lend itself to oop which requires a bit more thought and planning. Purists might be wagging their academic fingers at this point but these are people who have probably never had a quote accepted on elance!

It's worth looking at the advantages that a little oop can bring to Classic Active Server Pages.

These include:

  • code reuse

  • the ability to add and alter functionality without breaking the applications using the classes

  • encapsulation - hiding complex functionality


Here then I will show how to produce classes with properties that can be used multiple applications.

Creating a Simple VBScript Class in ASP

A class in VBScript is defined by using the Class...End Class key words, e.g:

Class Persona


End Class



This creates a empty class, but is not of much used yet. We need to add properties to it that define exactly what the class is meant to be modelling:




Class Persona


public age

public gender

End Class

You should be aware that elements of the class can be either:



•public - available to all users of the class

•private - only available within the class itself


It's also worth storing the class in its own server side include file at this point so that it can be reused again and again in different web sites. So, for example the code above could be stored in the file "persona.inc" and it's then ready for use.


Using VBScript Classes


Now the class is in it's own file it can be accessed in an ASP page using a server side include e.g:



The class can then be instantiated as an object by using the "new" method:


Set Freda = New persona

Set Petra = New persona


Here two persona objects (Freda and Petra - O.K. I used to watch Blue Peter!!) have been created, and so their properties can be set:


With Fred

.age = 21

.gender = "male"

End With

With Mary

.age = 22

.gender = "female"

End With


Now these properties can be used elsewhere in the web page:


response.write("Freda is a " & Freda.age & " year old " & Freda.gender)

response.write("
;Petra is a " & Petra.age & " year old " & Petra.gender)

Save the web page and the include and then view the page. The output should look something like this:

Freda is a 23 year old female

Petra is a 19 year old female



No comments: