Log In    |    Knowledge Base    |    4D Home
Tech Tip: User This Keyword to access Object properties in Object Formula
Published On: February 28, 2019
Your current browser may not allow you to download the asset. We recommend Mozilla Firefox or Google Chrome.
Log In

One of new features in V17 R3 is the addition of new Command New Formula. It creates an object formula based on the formula expression. It also allows adding a formula as property of object and can be invoked using object notation sytax. For example:

$f:=New formula(1+2)
$o:=New object("myFormula";$f)
$o.myFormula() //returns 3

Besides quick and easy access, assigning formula as property to an object has another advantage: it allows access of the entire object within the formula’s context using the keyword This. For example:

$o:=New object("Name";"John";"Age";20)
$o.myFomular:=New formula(This[$1]:=$2)
// {"Name":"John","Age":20,"myFomular":"[object Formula]"}

$o.myFomular("Age";23) // {"Name":"John","Age":23,"myFomular":"[object Formula]"}
$o.myFomular("Name";"Jack") // {"Name":"Jack","Age":23,"myFomular":"[object Formula]"}

The key word in the formula refers to $o object and has full access to every property. It enables the formula to work with the data of its outer object. Below is an example to add a formula to calculate birthyear based on the age of a person:

$person:=New object("Name";"John";"Age";20)
$person.getBirthYear:=New formula(Year of(Current date) -This.Age)
//result: 1999
//result: 1989

The ability to execute formula on an object offers a clean way to organize code and access its properties offers a clean way to calculate result based on object data dynamically.