Métodos
A 4D.Method object contains a piece of code that is created from text source and can be executed. 4D.Method methods always execute in interpreted mode, regardless of the project running mode (interpreted/compiled). This feature is especially designed to support dynamic, on-the-fly execution of code snippets.
A 4D.Method object is created with the 4D.Method.new() function.
4D.Method objects inherit from the 4D.Function class. Thus, to execute the method object, you can:
- store a
4D.Methodobject in an object property and use the()operator after the property name, - or directly call the
4D.Methodobject using thecall()orapply()function on it.
See examples in the Executing code in Function objects paragraph.
Exemplos
Basic dynamic method creation
var $myCode : Text
$myCode:="#DECLARE ($number1:Integer;$number2:Integer):Integer"+Char(13)+"return $number1*$number2"
var $o:={}
$o.multiplication:=4D.Method.new($myCode) //put object in a property
var $result2:=$o.multiplication(2;3) // 6
var $result3:=4D.Method.new($myCode).call(Null; 10; 5) // 50
Using This inside method code
var $myCode:="#DECLARE ($str1:text):text"+Char(13)+"return $str1+This.name"
var $o:={name: "John"}
$o.concat:=4D.Method.new($myCode)
var $result : Text
$result:=$o.concat("Hello ") // $result is "Hello John"
Using a text file with syntax checking
//4d method stored in a text file
var $newBusinessRules:=New shared object
Use ($newBusinessRules)
$newBusinessRules.taxRate:=0.2
$newBusinessRules.discountFormula:="price * quantity * discountRate"
$newBusinessRules.approvalThreshold:=10000
$newBusinessRules.freeShippingThreshold:=150
$newBusinessRules.defaultCurrency:="EUR"
End use
Use (Storage)
Storage.businessRules:=$newBusinessRules
End use
This method is called in the code:
var $myFile:=File("/DATA/BusinessRules.4dm")
var $myMethod:=4D.Method.new($myFile.getText())
// Syntax errors verification
If ($myMethod.checkSyntax().success)
$myMethod.call()
End if
Method Object
4D.Method objects provide the following properties and functions:
| .apply() : any .apply( thisObj : Object { ; params : Collection } ) : any executes the function object to which it is applied, passing parameters as a collection, and returns the resulting value |
| .call() : any .call( thisObj : Object { ; ...params : any } ) : any executes the function object to which it is applied, with one or more parameter(s) passed directly, and returns the resulting value |
| .checkSyntax() : Object checks the syntax of the source code of the 4D.Method object and returns a result object |
| .name : Text contains the name of the 4D.Method object, if it was declared in the name parameter of the new() constructor |
| .source : Text contains the source code of the function as text |
4D.Method.new()
História
| Release | Mudanças |
|---|---|
| 21 R3 | Adicionado |
4D.Method.new( source : Text {; name : Text } ) : 4D.Method
| Parâmetro | Tipo | Descrição | |
|---|---|---|---|
| source | Text | -> | Textual representation of a 4D method to be encapsuled as an object |
| name | Text | -> | Name of the method to display in the debugger. If omitted, the method name will be displayed as "anonymous" |
| Resultados | 4D.Method | <- | New Method shared object |
Descrição
The 4D.Method.new() function creates and returns a new 4D.Method object built from the source code.
In the source parameter, pass the 4D source code of the method as text. All end-of-line characters are supported (LF, CR, CRLF) using the Char command or an escape sequence.
In the optional name parameter, pass the name of the method to be displayed in the 4D debugger or Runtime explorer. If you omit this parameter, the method name will appear as "anonymous".
Giving a name to your method is recommended if you want to:
- use persistent method name in the Custom watch pane of the Debugger (anonymous methods are not persistent in the debugger).
- handle the volatile method using commands such as
Method get pathandMethod resolve path(anonymous methods don't have paths).
The resulting 4D.Method object can be checked using checkSyntax() and executed using (), .apply() or .call().
Named volatile method objects are not project methods, they are not stored in disk files and cannot be called by commands such as EXECUTE METHOD. On the other hand, since they inherit from the 4D.Function class, they can be used wherever a 4D.Function object is expected.
Exemplo
var $m:=4D.Method.new("#DECLARE ($t : Text) : Text \nreturn Uppercase($t)")
var $res:=$m.call(Null; "hello world") //HELLO WORLD
.apply()
História
| Release | Mudanças |
|---|---|
| 21 R3 | Support of 4D.Methods objects |
| 17 R3 | Adicionado |
.apply() : any
.apply( thisObj : Object { ; params : Collection } ) : any
| Parâmetro | Tipo | Descrição | |
|---|---|---|---|
| thisObj | Object | -> | Object to be returned by the This command in the function |
| params | Collection | -> | Collection of values to be passed as parameters to the function |
| Resultados | any | <- | Value from function execution |
Descrição
The .apply() function executes the function object to which it is applied, passing parameters as a collection, and returns the resulting value.
In the thisObj parameter, you can pass a reference to the object to be used as This within the function. Pass Null if you do not want to use This but you want to send parameters.
You can pass a collection to be used as parameters in the function using the optional params parameter:
- in
4D.Formulaobjects, parameters are passed in $1...$n in the formula. - in other
4D.Functionobjects such as4D.Methodobjects, parameters are passed in declared method parameters.
Note que .apply() é similar a .call() exceto que os parâmetros são passados como coleção. Isso pode ser útil para passar resultados calculados. Isso pode ser útil para passar resultados calculados.
Exemplo
var $coll:=[10; 2]
var $myCode:="#DECLARE ($number1:Integer;$number2:Integer):Integer\n"+\
"return $number1*$number2"
$m:=4D.Method.new($myCode; "m_multiple")
var $result:=$m.apply(Null; $coll) //20
.call()
História
| Release | Mudanças |
|---|---|
| 21 R3 | Support of 4D.Methods objects |
| 17 R3 | Adicionado |
.call() : any
.call( thisObj : Object { ; ...params : any } ) : any
| Parâmetro | Tipo | Descrição | |
|---|---|---|---|
| thisObj | Object | -> | Object to be returned by the This command in the function |
| params | any | -> | Values to be passed as parameters to the function |
| Resultados | any | <- | Value from function execution |
Descrição
The .call() function executes the function object to which it is applied, with one or more parameter(s) passed directly, and returns the resulting value.
In the thisObj parameter, you can pass a reference to the object to be used as This within the function.
You can pass values to be used as parameters in the function using the optional params parameter:
- in
4D.Formulaobjects, parameters are passed in $1...$n in the formula. - in
4D.Methodobjects, parameters are passed in declared method parameters.
Observe que .call() é semelhante a .apply(), exceto pelo fato de que os parâmetros são passados diretamente.
Exemplo
var $m : 4D.Method
var $myCode:="#DECLARE ($number1:Integer;$number2:Integer):Integer\n"+\
"return $number1*$number2"
$m:=4D.Method.new($myCode; "m_multiple")
var $result:=$m.call(Null; 10; 5) //50
.checkSyntax()
História
| Release | Mudanças |
|---|---|
| 21 R3 | Adicionado |
.checkSyntax() : Object
| Parâmetro | Tipo | Descrição | |
|---|---|---|---|
| Resultados | Object | <- | Syntax check result object |
Descrição
The .checkSyntax() function checks the syntax of the source code of the 4D.Method object and returns a result object.
The Result object contains the following properties:
| Propriedade | Tipo | Descrição | |
|---|---|---|---|
| success | Parâmetros | True if no syntax error was detected, false otherwise | |
| errors | Uma coleção de objetos | Disponível apenas em caso de erro ou aviso. Collection of objects describing errors or warnings | |
| [].isError | Parâmetros | Erro se Verdadeiro, aviso caso contrário | |
| [].message | Text | Error or warning message | |
| [].lineNumber | Integer | Número de erro da linha no código |
Exemplo
var $m : 4D.Method
var $check : Object
$m:=4D.Method.new("var $a:=2026\r$a:=current date")
$check:=$m.checkSyntax()
If ($check.success=False)
ALERT("Syntax error: "+$check.errors[0].message)
End if
.name
História
| Release | Mudanças |
|---|---|
| 21 R3 | Adicionado |
.name : Text
Descrição
The .name property contains the name of the 4D.Method object, if it was declared in the name parameter of the new() constructor. Otherwise, the property is not returned.
Essa propriedade é somente leitura.
.source
História
| Release | Mudanças |
|---|---|
| 21 R3 | Support of 4D.Methods objects |
| 18 R2 | Adicionado |
.source : Text
Descrição
The .source property contains the source code of the function as text.
The returned value is the original text used to create the 4D.Formula or 4D.Method object but reformatted.
Essa propriedade é somente leitura.
Exemplo
var $myCode:="#DECLARE ():Real\n"+\
"return random*current time"
$m:=4D.Method.new($myCode)
$src:=$m.source //"#DECLARE() : Real\rreturn Random*Current time"