Skip to main content

$this Syntax

$this Syntax

The $this variable provides a handle to the OREF of the current instance, such as for passing it to another class or for another class to refer to the properties or methods of the current instance. When an instance refers to its own properties or methods, relative dot syntax is faster and thus is preferred.

Note:

$this is not case-sensitive; hence, $this, $This, $THIS, or any other variant all have the same value.

For example, suppose there is an application with an Accounting.Order class and an Accounting.Utils class. The Accounting.Order.CalcTax() method calls the Accounting.Utils.GetTaxRate() and Accounting.Utils.GetTaxableSubtotal() methods, passing the city and state values of the current instance to the GetTaxRate() method and passing the list of items ordered and relevant tax-related information to GetTaxableSubtotal(). CalcTax() then uses the values returned to calculate the sales tax for the order. Hence, its code is something like:

Method CalcTax() As %Numeric
{
    Set TaxRate = ##class(Accounting.Utils).GetTaxRate($this)
    Write "The tax rate for ",..City,", ",..State," is ",TaxRate*100,"%",!
    Set TaxableSubtotal = ##class(Accounting.Utils).GetTaxableSubTotal($this)
    Write "The taxable subtotal for this order is $",TaxableSubtotal,!
    Set Tax = TaxableSubtotal * TaxRate
    Write "The tax for this order is $",Tax,!
}

The first line of the method uses the ##Class syntax (described above) to invoke the other method of the class; it passes the current object to that method using the $this syntax. The second line of the method uses relative dot syntax to get the values of the City and State properties. The action on the third line is similar to that on the first line.

In the Accounting.Utils class, the GetTaxRate() method can then use the handle to the passed-in instance to get handles to various properties — for both getting and setting their values:

ClassMethod GetTaxRate(OrderBeingProcessed As Accounting.Order) As %Numeric
{
    Set LocalCity = OrderBeingProcessed.City
    Set LocalState = OrderBeingProcessed.State
    // code to determine tax rate based on location and set
    // the value of OrderBeingProcessed.TaxRate accordingly
    Quit OrderBeingProcessed.TaxRate
}

The GetTaxableSubtotal() method also uses the handle to the instance to look at its properties and set the value of its TaxableSubtotal property.

Hence, the output at the Terminal from invoking the CalcTax() method for MyOrder instance of the Accounting.Order class would be something like:

>Do MyOrder.CalcTax()
The tax rate for Cambridge, MA is 5%
The taxable subtotal for this order is $79.82
The tax for this order is $3.99
FeedbackOpens in a new tab