While the "this%" class holds variables of the object, there is no equivalent construct to hold another object within an object. However, this can be worked around by context linking into the constructor's local context.
The constructor is a function to create the object. It can also create other objects in its local context. These "member" object can be in possession of the "main" object.
However, once the constructor exists, the local context is lost and gone with the "member" object. One way to keep the context (and therefore any "member" objects in it) alive is to save the context into an object variable (e.g. this%context). Subsequent calls to the object's methods can reacquire access to the constructor's local context (and therefore the "member" objects in it).
function person
{
var this%name = "{arg%name}";
}
function car
{
var this%context = "{sys%context}"; // Save context
var ownerobj = new person name="{arg%name}"; // An object name
var this%make = "{arg%make}"; // A string
var this%function:belongsto = "car_belongsto";
}
function car_belongsto
{
// Link "ownerobj" from "car"'s local context to the current one.
var ownerobj% =& ownerobj% context="{this%context}";
display "This {this%make} belongs to {ownerobj%name}";
}
var myCar = new car make="Ford" name="John Lee";
myCar%belongsto; // This Ford belongs to John Lee
Sometimes, you may not want to keep the object externally and pass to the object method when calling. In that case, the "parent" command is required to access the external object from the method.
function car
{
var this%make = "{arg%make}"; // A string
var this%function:belongsto = "car_belongsto";
}
function car_belongsto
{
parent "{arg%owner}%"; // The owner object is from the parent
display "This {this%make} belongs to {{arg%owner}%name}";
}
var jl = new person name="John Lee";
var myCar = new car make="Ford";
myCar%belongsto owner="jl";
The need for a "parent" command is not always obvious. For example, if the method does not access the external object but calls another function that does, "parent" is still required in the method function to "pass on" the linkage.
function car_belongsto
{
parent "{arg%owner}%"; // This is required to pass on
this%car_ownersname owner="{arg%owner}";
display "This {this%make} belongs to {result%car_ownersname}";
}
function car_ownersname
{
parent "{arg%owner}%"; // linked to the caller's context
var result%function = "{{arg%owner}%name}";
}
In "car_ownersname", the {arg%owner}% is linked to the same variable in the caller's context. If "parent" is missing from "car_belongsto", "car_ownersname" will link to no object.
|