About Methods
A method is a special kind of property that simply points to a function. Usually, the function is designed to operate on the data contained in the object.
For example, assume you want to modify the Customer object to include a function that returns the customer's mailing address as it should be printed on a mailing label. The Customer object already includes the fields that make up this address, but not in the proper form.
You can build a separate function that constructs the address as follows:
Customer_mailingaddress(obj):=
obj.name+"\n"+
obj.address+"\n"+
obj.city+" "+obj.state+" "+obj.zipcode
This function accepts a Customer object as the input argument and then constructs an address by concatenating the proper fields in the proper order. You can call this function as follows:
A better approach is to make the mailingaddress function part of the object itself. To do this, you must modify the Customer object constructor to define one additional property as follows:
Customer(name):={
.name=name;
.address="";
.city="";
.state="";
.zipcode=0;
.phonenumber="";
.mailingaddress=Customer_mailingaddress;
}
Next, you modify the function Customer_mailingaddress to replace all occurrences of the argument obj with a reference to this and remove the input argument.
Customer_mailingaddress(none):=
this.name+"\n"+
this.address+"\n"+
this.city+" "+this.state+" "+this.zipcode
See this.
Remember that using the keyword for this is optional in DScript, so you can simplify the definition as follows:
Now, you can get the mailing address for any Customer object by calling the object's mailingaddress method:
When you execute an object's method, the keyword this points to is the object itself. This frees you from having to pass the object as an argument.
Note that even though the function Customer_mailingaddress accepts no arguments, the function is defined with one dummy argument named none. This is done to ensure Customer_mailingaddress is defined as a function rather than a constant. If Customer_mailingaddress had been defined as
or
the last line in the object constructor
would have set the property mailingaddress equal to the value of Customer_mailingaddress instead of setting it equal to a pointer to the function.