Método
A 4D.Method object contains a piece of code that is created from text source and can be executed. Los métodos 4D.Method siempre se ejecutan en modo interpretado, independientemente del modo de ejecución del proyecto (interpretado/compilado). Esta funcionalidad está especialmente diseñada para permitir la ejecución dinámica y sobre la marcha de fragmentos de código.
Un objeto 4D.Method se crea con la función 4D.Method.new().
4D.Method objects inherit from the 4D.Function class. Así, para ejecutar el objeto método, puede:
- store a
4D.Methodobject in an object property and use the()operator after the property name, - o llamar directamente al objeto
4D.Methodusando la funcióncall()oapply()en él.
Ver ejemplos en el párrafo Ejecución de código en los objetos Function.
Ejemplos
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
Uso de This dentro del código del método
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"
Utilizar un archivo de texto con comprobación sintáctica
//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
Este método se llama en el código:
var $myFile:=File("/DATA/BusinessRules.4dm")
var $myMethod:=4D.Method.new($myFile.getText())
// Syntax errors verification
If ($myMethod.checkSyntax().success)
$myMethod.call()
End if
Objeto Método
Los objetos 4D.Method ofrecen las siguientes propiedades y funciones:
| .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 contiene el código fuente de la función como texto |
4D.Method.new()
Historia
| Lanzamiento | Modificaciones |
|---|---|
| 21 R3 | Añadidos |
4D.Method.new( source : Text {; name : Text } ) : 4D.Method
| Parámetros | Tipo | Descripción | |
|---|---|---|---|
| source | Text | -> | Representación textual de un método 4D a encapsularse como un objeto |
| name | Text | -> | Nombre del método a mostrar en el depurador. Si se omite, el nombre del método se mostrará como "anonymous" |
| Resultado | 4D.Method | <- | Nuevo método objeto compartido |
Descripción
The 4D.Method.new() function creates and returns a new 4D.Method object built from the source code.
En el parámetro source, pase el código fuente 4D del método como texto. All end-of-line characters are supported (LF, CR, CRLF) using the Char command or an escape sequence.
En el parámetro opcional name, pase el nombre del método que se mostrará en el depurador 4D o en el explorador Runtime. Si omite este parámetro, el nombre del método aparecerá como "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.
Ejemplo
var $m:=4D.Method.new("#DECLARE ($t : Text) : Text \nreturn Uppercase($t)")
var $res:=$m.call(Null; "hello world") //HELLO WORLD
.apply()
Historia
| Lanzamiento | Modificaciones |
|---|---|
| 21 R3 | Soporte de objetos 4D.Methods |
| 17 R3 | Añadidos |
.apply() : any
.apply( thisObj : Object { ; params : Collection } ) : any
| Parámetros | Tipo | Descripción | |
|---|---|---|---|
| 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 |
| Resultado | any | <- | Valor de la ejecución de la función |
Descripción
The .apply() function executes the function object to which it is applied, passing parameters as a collection, and returns the resulting value.
En el parámetro thisObj, puede pasar una referencia al objeto que se utilizará como This en la función. Pasa Null si no quiere utilizar This pero quiere enviar parámetros.
Puede pasar una colección para utilizarla como parámetros en la función utilizando el parámetro opcional params:
- en los objetos
4D.Formula, los parámetros se pasan en $1...$n en la fórmula. - in other
4D.Functionobjects such as4D.Methodobjects, parameters are passed in declared method parameters.
Tenga en cuenta que .apply() es similar a .call() excepto que los parámetros se pasan como una colección. Esto puede ser útil para pasar los resultados calculados.
Ejemplo
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()
Historia
| Lanzamiento | Modificaciones |
|---|---|
| 21 R3 | Soporte de objetos 4D.Methods |
| 17 R3 | Añadidos |
.call() : any
.call( thisObj : Object { ; ...params : any } ) : any
| Parámetros | Tipo | Descripción | |
|---|---|---|---|
| thisObj | Object | -> | Object to be returned by the This command in the function |
| params | any | -> | Valores a pasar como parámetros a la función |
| Resultado | any | <- | Valor de la ejecución de la función |
Descripción
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.
En el parámetro thisObj, puede pasar una referencia al objeto que se utilizará como This en la función.
You can pass values to be used as parameters in the function using the optional params parameter:
- en los objetos
4D.Formula, los parámetros se pasan en $1...$n en la fórmula. - en los objetos
4D.Method, los parámetros se pasan en parámetros declarados.
Tenga en cuenta que .call() es similar a .apply() excepto que los parámetros se pasan directamente.
Ejemplo
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()
Historia
| Lanzamiento | Modificaciones |
|---|---|
| 21 R3 | Añadidos |
.checkSyntax() : Object
| Parámetros | Tipo | Descripción | |
|---|---|---|---|
| Resultado | Object | <- | Syntax check result object |
Descripción
The .checkSyntax() function checks the syntax of the source code of the 4D.Method object and returns a result object.
El objeto devuelto contiene las siguientes propiedades:
| Propiedad | Tipo | Descripción | |
|---|---|---|---|
| success | Boolean | True if no syntax error was detected, false otherwise | |
| errors | Colección de objetos | Disponible sólo en caso de error o de warning. Colección de objetos que describen errores o advertencias | |
| [].isError | Boolean | Error si es True, sino warning | |
| [].message | Text | Mensaje de error o advertencia | |
| [].lineNumber | Integer | Número de línea del error en el código |
Ejemplo
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
Historia
| Lanzamiento | Modificaciones |
|---|---|
| 21 R3 | Añadidos |
.name : Text
Descripción
The .name property contains the name of the 4D.Method object, if it was declared in the name parameter of the new() constructor. En caso contrario, no se devuelve la propiedad.
Esta propiedad es de solo lectura.
.source
Historia
| Lanzamiento | Modificaciones |
|---|---|
| 21 R3 | Soporte de objetos 4D.Methods |
| 18 R2 | Añadidos |
.source : Text
Descripción
La propiedad .source contiene el código fuente de la función como texto.
El valor devuelto es el texto original utilizado para crear el objeto 4D.Formula o 4D.Method pero reformateado.
Esta propiedad es de solo lectura.
Ejemplo
var $myCode:="#DECLARE ():Real\n"+\
"return random*current time"
$m:=4D.Method.new($myCode)
$src:=$m.source //"#DECLARE() : Real\rreturn Random*Current time"