This is the legacy 4D documentation web site. Documentations are progressively being moved to developer.4d.com

Home

 
4D v20.6
Using object notation

Using object notation  


 

You can handle 4D language objects using the object notation to get or to set their values. For compatibility reasons, this feature requires that you explicitly activate a compatibility option. Once object notation is activated, you can use it everywhere in 4D where expressions are expected.

Each property value accessed through object notation is considered an expression. When object notation is enabled in your database (see below), you can use such values wherever 4D expressions are expected:

  • in 4D code, either written in the methods (Method editor) or externalized (formulas, 4D tags files processed by PROCESS 4D TAGS or the Web Server, export files, 4D Write Pro documents, etc.),
  • in the Expression areas of the Debugger and the Runtime explorer,
  • in the Property list of the Form editor for form objects: Variable or Expression field as well as various selection list box and columns expressions (Data Source, background color, style, or font color).

Objects manipulated via object notation must have been initialized, for example using the New object command, otherwise trying to read or modify their properties will generate a syntax error.

Example:

 C_OBJECT($obVar//creation of an object type 4D variable
 $obVar:=New object //initialization of the object and assignment to the 4D variable

The same principle applies to Object type fields:

 CREATE RECORD([Person]) //Adding a new record to a table containing an object field
 [Person]Data_o:=New object //Initialization of the object and assignment to the 4D field

Object notation can be used to access object property values and collection elements through a chain of tokens.

With object notation, object properties can be accessed in two ways:

  • using a "dot" symbol:
    object.propertyName

    Example:
     employee.name:="Smith"
  • using a string within square brackets:
    object["propertyName"]

    Example:
     $vName:=employee["name"]

Since an object property value can be an object or a collection, object notation accepts a sequence of symbols to access sub-properties, for example:

 $vAge:=employee.children[2].age

Object notation is available on any language element that can contain or return an object, i.e.:

  • Objects themselves (stored in variables, fields, object properties, object arrays, or collection elements).
    Examples:
     $age:=$myObjVar.employee.age //variable
     $addr:=[Emp]data_obj.address //field
     $city:=$addr.city //property of an object
     $pop:=$aObjCountries{2}.population //object array
     $val:=$myCollection[3].subvalue //collection element
  • 4D commands that return objects.
    Example:
     $measures:=Get database measures.DB.tables
  • Project methods that return objects.
    Example:
      // MyMethod1
     C_OBJECT($0)
     $0:=New object("a";10;"b";20)
     
      //myMethod2
     $result:=MyMethod1.a //10
  • Collections
    Example:
     myColl.length //size of the collection
     maxSal:=myColl.max("salary")

To access a collection element, you have to pass the element number embedded in square brackets:

collectionName[expression]

Note: For more information on collection type variables, please refer to the Collection section. 

You can pass any valid 4D expression that return a positive integer in expression. Examples:

 myCollection[5]  //access to 6th element of the collection
 myCollection[$var]

Note: Keep in mind that collection elements are numbered from 0.

You can assign a value to a collection element using the object notation:

 myCol[10]:="My new element"

If this element index is beyond the last existing element of the collection, the collection is automatically resized and all new intermediary elements get the null value:

 C_COLLECTION(myCol)
 myCol:=New collection("A";"B")
 myCol[5]:="Z"
  //myCol[2]=null
  //myCol[3]=null
  //myCol[4]=null

Length property

The length property is available automatically for all collections and returns the size of the collection, i.e. the number of elements it contains. You can access this property in two ways:

  • using a "dot" symbol, for example:
     $vSize:=myCollection.length
  • using a string within square brackets, for example:
     $vSize:=myCollection["length"]

Note that the length property can only be read, it cannot be modified.

Property values can be accessed through pointers. Using object notation with pointers is very similar to using object notation directly with objects, except that the "dot" symbol must be omitted.

  • Direct access:
    pointerOnObject->propertyName
  • Access by name:
    pointerOnObject->["propertyName"]

Example:

 C_OBJECT(vObj)
 C_POINTER(vPtr)
 vObj:=New object
 vObj.a:=10
 vPtr:=->vObj
 x:=vPtr->a //x=10

When using object notation, the null value is supported though the Null command. This command can be used to assign or compare the null value to object properties or collection elements, for example:

 myObject.address.zip:=Null
 If(myColl[2]=Null)

For more information, please refer to the Null command description.

Evaluating an object property can sometimes produce an undefined value. Typically when trying to read or assign undefined expressions, 4D will generate errors. This does not happen in the following cases:

  • Reading a property of an undefined object or value returns undefined; assigning an undefined value to variables (except arrays) has the same effect as calling CLEAR VARIABLE with them:
     C_OBJECT($o)
     C_LONGINT($val)
     $val:=10 //$val=10
     $val:=$o.a //$o.a is undefined (no error), and assigning this value clears the variable
      //$val=0
  • Reading the length property of an undefined collection produces 0:
     C_COLLECTION($c//variable created but no collection is defined
     $size:=$c.length //$size = 0
  • An undefined value passed as parameter to a project method is automatically converted to 0 or "" according to the declared parameter type.
     C_OBJECT($o)
     mymethod($o.a) //pass an undefined parameter
     
      //In mymethod method
     C_TEXT($1//parameter type is text
      // $1 contains ""
  • A condition expression is automatically converted to false when evaluating to undefined with the If and Case of keywords:
     C_OBJECT($o)
     If($o.a) // false
     End if
     Case of
        :($o.a) // false
     End case
  • Assigning an undefined value to an existing object property reinitializes or clears its value, depending on its type:
    • Object, collection, pointer: Null
    • Picture: Empty picture
    • Boolean: False
    • String: ""
    • Number: 0
    • Date: !00-00-00! if "Use date type instead of ISO date format in objects" setting is enabled, otherwise ""
    • Time: 0 (number of ms)
    • Undefined, Null: no change

     C_OBJECT($o)
     $o:=New object("a";2)
     $o.a:=$o.b //$o.a=0

  • Assigning an undefined value to a non existing object property does nothing.

When expressions of a given type are expected in your 4D code, you can make sure they have the correct type even when evaluated to undefined by surrounding them with the appropriate 4D cast command: String, Num, Time, Date, Bool. These commands return an empty value of the specified type when the expression evaluates to undefined. For example:

 $myString:=Lowercase(String($o.a.b)) //make sure you get a string value even if undefined
  //to avoid errors in the code

The Formula or Formula from string commands allow you to create native "formula" objects that you can encapsulate in object properties:

 C_OBJECT($f)
 $f:=New object
 $f.message:=Formula(ALERT("Hello world"))

Such properties are "object methods", i.e. methods which are bound to their parent object. To execute a method stored in an object property, use the ( ) operator after the property name, such as:

 $f.message() //displays "Hello world"

Syntax with brackets is also supported:

 $f["message"]() //displays "Hello world"

You can also pass parameters to your formula when you call it by using $1, $2… just like with 4D project methods:

 C_OBJECT($f)
 $f:=New object
 $f.message:=Formula(ALERT("Hello "+$1))
 $f.message("John") //displays "Hello John"

Note that, even if it does not have parameters, an object method to be executed must be called with ( ) parenthesis. Calling only the object property will return a new reference to the formula (and will not execute it):

 $o:=$f.message //returns the formula object in $o

Token member names (i.e., object property names accessed using object notation) are more restrictive than standard 4D object names. They must comply with JavaScript Identifier Grammar (see ECMA Script standard):

  • the first character must be a letter, an underscore (_), or a dollar sign ($),
  • subsequent characters may be any letter, digit, an underscore or dollar sign (space characters are NOT allowed),
  • they are case sensitive.

Notes:

  • Using a table field as a collection index, for example a.b[[Table1]Id], is not allowed. You must use an intermediary variable.
  • Creating object attributes using a string in square brackets allows you to override the ECMA Script rules. For example, the $o["My Att.name"] attribute is valid in 4D, despite the space. In this case, however, it will not be possible to use dot notation with this attribute.

Warning
Although object property names can contain special characters such as "." or "[ ]" (and are available through the $o["My Att.name"] syntax), they are not recommended since you will not be able to perform queries or sorts on them. All 4D commands and methods that execute queries on object properties, such as dataClass.query( ) or QUERY BY ATTRIBUTE use a string as propertyPath or attributePath parameter, for example:

 QUERY BY ATTRIBUTE([People];[People]Animals;"dog.name";#;"Rex") //name subproperty of dog

Queries and sorts on using properties that have special characters in their name could be incorrectly interpreted and give invalid results. For example, if you defined a property named ["A.1.1"], it will not be possible to query:

 QUERY BY ATTRIBUTE([Chapter];[Chapter]code;"A.1.1";=;"Intro@") //property name will be interpreted as a path

Over any versions, 4D has always accepted dots (.) and square brackets ([ and ]) in tokenized database object names (tables, fields, variables, and methods). 

However, these characters are used to identify language tokens in standard object notation. Thus, databases using names containing dots or square brackets are not compatible with the standard object notation since misinterpretations could break existing code. For example, if the following code is written:

a.b
a.b:=c[1]

...4D could not know if a.b and c[1] represent standard variable names or if b is a property of the a object and c the second element of a c collection. 

Consequently:

  • In databases converted from versions prior to 4D v17, you have to select a specific compatibility setting (see below) that you want to use the object notation. By selecting this option, you declare that your code is "object notation ready", that is, it does not use any names containing "." or "[]" characters.
  • A specific MSC feature helps you detect names which are incompatible with object notation. Using this feature is highly recommended before enabling the option (see the Verify page section of the "MSC" chapter). As usual, it is recommended to work on a copy of the structure file.
  • Starting with 4D v17 (v16 R4), entering "." and "[]" characters in names of tokenized objects is no longer allowed. 

To be able to use object notation in databases created in versions prior to 4D v17, you must select the Use object notation to access object properties (Unicode required) option in the Compatibility page of the Database settings dialog box:

For more information about this setting, please refer to the Compatibility page.

Note: Components can have a different setting from the host database.

Using object notation simplifies the 4D code while handling objects. Note however that the command-based notation is still fully supported.

  • Writing and reading objects (this example compares object notation and command notation):

  // Using the object notation
 C_OBJECT($myObj//declares a 4D variable object
 $myObj:=New object //creates an object and assigns to the variable
 $myObj.age:=56
 $age:=$myObj.age //56
 
  // Using the command notation
 C_OBJECT($myObj2//declares a 4D variable object
 OB SET($myObj2;"age";42) //creates an object and adds the age property
 $age:=OB Get($myObj2;"age") //42
 
  // Of course, both notations can be mixed
 C_OBJECT($myObj3)
 OB SET($myObj3;"age";10)
 $age:=$myObj3.age //10

  • Create a property and assign values, including objects:

 C_OBJECT($Emp)
 $Emp:=New object
 $Emp.city:="London" //creates the city property and sets its value to "London"
 $Emp.city:="Paris" //modifies the city property
 $Emp.phone:=New object("office";"123456789";"home";"0011223344")
  //creates the phone property and sets its value to an object

  • Get a value in a sub-object is very simple using the object notation:

 $vCity:=$Emp.city //"Paris"
 $vPhone:=$Emp.phone.home //"0011223344"

  • You can access properties as strings using the [ ] operator

 $Emp["city"]:="Berlin" //modifies the city property
  //this can be useful for creating properties through variables
 C_TEXT($addr)
 $addr:="address"
 For($i;1;4)
    $Emp[$addr+String($i)]:=""
 End for
  // creates 4 empty properties "address1...address4" in the $Emp object



See also 

C_COLLECTION
C_OBJECT
New collection
New object
Object Notation Analysis Errors (-10737 -> -10701)

 
PROPERTIES 

Product: 4D
Theme: Objects (Language)

 
PAGE CONTENTS 
 
HISTORY 

Created: 4D v16 R4

 
ARTICLE USAGE

4D Language Reference ( 4D v20)
4D Language Reference ( 4D v20.1)
4D Language Reference ( 4D v20.2)
4D Language Reference ( 4D v20.3)
4D Language Reference ( 4D v20.4)
4D Language Reference ( 4D v20.5)
4D Language Reference ( 4D v20.6)