classes and javaScript

Creating and working with classes in VBA is very different from working with js classes. In fact, JavaScript is a classless language - there is no such thing as a class. This is not so scary as it sounds though, as there are various ways to make JavaScript behave as if there were.

Allocating memory for an instance of the class

VBA

Set dcell = New cCell

javaScript

var cc = new cCell();

Not so different there, but notice that the class in js is actually a call to a function. The constructor for this class looks like this, and if necessary any housekeeping associated with creating a new instance could be done inside this function. Note that defining a function in this way is the only time you need to put a semi-colon after the curly brackets (some interpreters don't care, but strictly speaking it should be there.

var cCell = function () {

};

Properties

In VBA there is a fair amount of fuss around declaring get/let/set properties, and the allocation private space for them inside the class instance, but there is a good reason for this - to be able to separate readonly from read/write properties. Here is a couple of properties of the cCell class

Option Explicit

private pValue As Variant ' value of cell when first loaded

private pColumn As Long ' column number

private pKeepFresh As Boolean ' update with value when accessed

private pParent As cDataRow ' cDataRow to which this belongs

Public Property Get Row() As Long

Row = pParent.Row

End Property

Public Property Get Column() As Long

Column = pColumn

End Property

in js, you declare a property just by mentioning it, but in doing so, it becomes readable and writable. Here is the .create method of the ccell class

by assigning values to this.column, this.parent etc., we create the property and can access it later.

Readonly properties

If you want to duplicate the behavior of VBA, you need to simulate the js class in another way. Here's an example protecting a private copy of a property and exposing its value through a related method. The only thing with this is that you would need to define all methods inside the constructor for this class (rather than extending the prototype), so that they could have the same visibility to the private property, as they have in VBA.

cCell = function() {

var pParent = 0;

this.parent = function() {

return pParent;

}

};

Methods

In VBA, public methods are procedures associated with that class and get associated simply by being in the same class module.

As previously mentioned, js doesn't really have classes but there are a few ways of simulating class-like behavior. I prefer to use a function to define a class constructor, and then add methods to that function's constructor using its prototype. You can see that in the create method above. Here is the entire ccell class converted to google apps script. It ends up being more concise than the VBA version.