Saltar al contenido principal
Versión: Siguiente

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.Method object in an object property and use the () operator after the property name,
  • o llamar directamente al objeto 4D.Method usando la función call() o apply() en él.

Ver ejemplos en el párrafo Ejecución de código en los objetos Function.

Entrada de blog relacionada

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
LanzamientoModificaciones
21 R3Añadidos

4D.Method.new( source : Text {; name : Text } ) : 4D.Method

ParámetrosTipoDescripción
sourceText->Representación textual de un método 4D a encapsularse como un objeto
nameText->Nombre del método a mostrar en el depurador. Si se omite, el nombre del método se mostrará como "anonymous"
Resultado4D.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".

tip

Giving a name to your method is recommended if you want to:

The resulting 4D.Method object can be checked using checkSyntax() and executed using (), .apply() or .call().

nota

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
LanzamientoModificaciones
21 R3Soporte de objetos 4D.Methods
17 R3Añadidos

.apply() : any
.apply( thisObj : Object { ; params : Collection } ) : any

ParámetrosTipoDescripción
thisObjObject->Object to be returned by the This command in the function
paramsCollection->Collection of values to be passed as parameters to the function
Resultadoany<-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.Function objects such as 4D.Method objects, 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
LanzamientoModificaciones
21 R3Soporte de objetos 4D.Methods
17 R3Añadidos

.call() : any
.call( thisObj : Object { ; ...params : any } ) : any

ParámetrosTipoDescripción
thisObjObject->Object to be returned by the This command in the function
paramsany->Valores a pasar como parámetros a la función
Resultadoany<-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
LanzamientoModificaciones
21 R3Añadidos

.checkSyntax() : Object

ParámetrosTipoDescripción
ResultadoObject<-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:

PropiedadTipoDescripción
successBooleanTrue if no syntax error was detected, false otherwise
errorsColección de objetosDisponible sólo en caso de error o de warning. Colección de objetos que describen errores o advertencias
[].isErrorBooleanError si es True, sino warning
[].messageTextMensaje de error o advertencia
[].lineNumberIntegerNú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
LanzamientoModificaciones
21 R3Añ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
LanzamientoModificaciones
21 R3Soporte de objetos 4D.Methods
18 R2Añ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"