Tech Tip: Objects Are References
PRODUCT: 4D | VERSION: 16 R | PLATFORM: Mac & Win
Published On: May 25, 2018
Objects (and object notation) are going to be a big part of 4D going forward. One important thing to understand about objects is that they are references. What does this mean exactly? Consider this simple scenario of three objects:
$obj_A:=New object("hello";"world") $obj_B:=$obj_A $obj_C:=OB Copy($obj_A) $obj_A.hello:="4D!" OB SET($obj_A;"welcome to";"object notation") $obj_B["welcome to"]:="the future" |
What will the outcome be after the above block of code is executed? Stepping through the code will show what is going on...
1) After setting up the object definitions, all three objects have the same key-value pairs.
$obj_A:=New object("hello";"world") $obj_B:=$obj_A $obj_C:=OB Copy($obj_A) ... |
2) Modifying $obj_A will also modify $obj_B, because B is a reference to A. Object $obj_C remains unchanged as it was a deep copy from $obj_A.
... $obj_A.hello:="4D!" OB SET($obj_A;"welcome to";"object notation") ... |
3) Modifing B will also modify A, because A is a reference to B!
... $obj_B["welcome to"]:="the future" |
So remember...if the object needs to be copied and manipulated as a separate object, then the OB Copy command should be used, as this command returns a deep copy of the object.