Você está na página 1de 23

1.

2.
3.
4.
5.
6.
7.

An object could consume a function which it does not own


Anonymous object
Overwrite builder-in code
Constructor redefinition
Comma and colon
Dynamically change inheritance relationship in the runtime
argument passing logic
built-in array Arguments in Javascript
Dynamic parameter passing in ABAP
Further discussion on ABAP function module passing approach
8. predefined data type and wrapper object if any
9. me in ABAP VS this in Javascript
More features to be added

There are already two great blogs which stress why ABAPers should learn
Javascript and some essential Javascript features.
Top 10 things ABAP developers should know when learning JavaScript
JavaScript for ABAP Developers
In this document, I will collect some interesting and useful Javascript features
compared with ABAP by using examples for demonstration. I will keep it
updated once I have learned new stuff.

1. An object could consume a function which it does not own


Paste this source code below into a new .html file and run it in Chrome.

1.

<html>

2.

<script>

3.

function ABAPDeveloper(name, year)

4.

5.

this.name = name;

6.

this.year = year;

7.

this.codeABAP = function() {

8.

console.log("Hello, my name is: " + this.name + " I have " + this.year

9.

+ " year's ABAP development experience");

10. }
11. }
12. function CDeveloper(name, year, os)
13. {
14. this.name = name;
15. this.year = year;
16. this.os = os;
17. this.codeC = function() {
18. console.log("Hello, my name is: " + this.name + " I have " + this.year
19. + " year's C development experience focus on " + os + " system.");
20. }
21. }
22. var iJerry = new ABAPDeveloper("Jerry", 7);
23. iJerry.codeABAP();
24. var iTom = new CDeveloper("Tom", 20, "Linux");
25. iTom.codeC();
26. iTom.codeC.call(iJerry);
27. </script>
28. </html>

All the codes are very easy to understand except this


"iTom.codeC.call(iJerry)".
As mentioned in Kevin Small's blog, "In JavaScript Functions are First Class",
we can consider currently Javascript uses the keyword "function" to

implement the OO concept with different approach than ABAP. In this


example, although Jerry has no C development experience, now I suddenly
owned 7 years' C development experience on Linux
Output in Chrome console:
Hello, my name is: Jerry I have 7 year's ABAP development experience
Hello, my name is: Tom I have 20 year's C development experience focus on
Linux system.
Hello, my name is: Jerry I have 7 year's C development experience focus on
Linux system.
If you debug in Chrome, you can find the magic of iTom.codeC.call(iJerry).
Here the function codeC owned by Object CDeveloper is called by explicitly
specifying the context as instance iJerry, this could be observed by checking
"this" variable in Chrome debugger, currently "this" points to instance iJerry.

This quite flexible feature is not available in ABAP. As we know, the class
instance in ABAP could only consume its own method or those inherited from
its parent.
2. Anonymous object
in below example, we define two simple functions a and b, and assign them
separately to variable d and e, so those two functions could also be called via
d and e as well. In the meantime, another anonymous function with one
argument name is also defined. in this context, there is no way to assign this
anonymous function to another variable, it has to be executed immediately
once having been defined. In this example it is called with argument name =
"c",

1.

<html>

2.

<p>hello</p>

3.

<script>

4.

function a() { console.log("I am function a");}

5.

function b() { console.log("I am function b");}

6.

var d = a;

7.

var e = b;

8.

a();

9.

b();

10. d();
11. e();
12. (function(name) { console.log("I am function: " + name); })("c");
13. </script>
14. </html>

Check the variable a , b, d, e in Chrome debugger. There is a tab


"anonymous function" which enables you to have a list of all anonymous
functions used.

Finally it generates output like below:


I am function a
I am function b
I am function a

I am function b
I am function: c
Go back to ABAP, since we don't treat function module as an object, and
every function module should have a name so that it could be called via
name.
And for the anonymous function in Javascript, since once it is defined and
executed, it could not be reused later, I personaly would like to compare this
"transient" feature with ABAP keyword GENERATE SUBROUTINE POOL itab
NAME prog. Just execute this code which could be found in ABAP help:

1.

DATA itab TYPE TABLE OF string.

2.

DATA prog TYPE string.

3.

DATA class TYPE string.

4.

DATA oref TYPE REF TO object.

5.

APPEND `program.`

6.

APPEND `class main definition.`

7.

APPEND ` public section.`

8.

APPEND `

9.

APPEND `endclass.`

methods meth.`

TO itab.
TO itab.
TO itab.
TO itab.
TO itab.

10. APPEND `class main implementation.` TO itab.


11. APPEND ` method meth.`
12. APPEND `

TO itab.

message 'Test' type 'I'.` TO itab.

13. APPEND ` endmethod.`


14. APPEND `endclass.`

TO itab.
TO itab.

15. GENERATE SUBROUTINE POOL itab NAME prog.


16. class = `\PROGRAM=` && prog && `\CLASS=MAIN`.

17. CREATE OBJECT oref TYPE (class).


18. CALL METHOD oref->('METH').

In the runtime, a temporary class type is created and it is allowed to create


new object instance based on this type. And this type is transient so could
only be used in current transaction.
3. Overwrite builder-in code
Let's review how could this be done in ABAP. It is one of the most powerful
abilities I appreciate in ABAP to change the behavior of standard code via
pre-exit, post-exit and overwrite-exit. It is a good tool especially for those
consultant working for customer project. By creating an overwrite-exit, you
can completely deactivate the standard method execution and make your
own exit run. For details about how to create the exit, please see
this document.

And in Javascript, it is even much easier to overwrite the build-in code.


Suppose I would like to rewrite the build-in function console.log.
Just paste this code below in the beginning of <script> node in example 2:

1.

var _log = console.log;

2.

console.log = function() {

3.

_log.call(console, '%c' + [].slice.call(arguments).join(' '), 'color:green;text-shadow:0 0 4px rgba(100,200,23,.


5);');

4.

};

execute example 2 again, the output is generated with our customized color:

4. Constructor redefinition
In ABAP it is not possible to redefine a constructor method.

You will receive a message when clicking redefine button in class builder:
"You cannot redefine the constructor".
However in Javascript, it is allowed to redefine a function implementation
inside itself, sounds crazy?
Let's first have a look at this small piece of code:

1.

<html

2.

</html>

3.

<script>

4.

function Person(name)

5.

{
this.name = name;

6.
7.

8.

var person1 = new Person("Jerry");

9.

var person2 = new Person("Jerry");

10. alert( person1 === person2 ? "Yes":"No");


11. </script>

it pops up No, since we use "===" comparator and person1 and person2 are
two different object instance.
Now inside function Person, I overwrite it by just return the buffered "this"
instance, so all the subsequent call of new Person will always return that
buffered instance, and this time I will save a pop up with Yes.
<html>
<script>
function Person(name) {
var instance = this;
this.name = name;
Person = function() {
return instance;

}
}
var iJerry1 = new Person("Jerry");
var iJerry2 = new Person("Jerry");
alert( iJerry1 === iJerry2 ? "Yes":"No");
</script>
</html>

5. Comma and colon


In example 2, you could call function a and b one by one with the following
code:

1.

a(), b();

And get the following output:


I am function a
I am function b
with the help of the so called comma expression, some interesting
requirement could be fulfilled.
For example, there is a famous interview question: how to exchange the
content of two INTEGER variables WITHOUT using intermediate variable?
Using comma expression in Javascript, this could be done via a simple line of
code:
<html>
</html>
<script>
var a =1,b=2;
a=[b,b=a][0];
console.log("a:" + a);
console.log("b:" + b);
</script>

output in Chrome console:


a:2
b:1

In ABAP the usage of comma like this is not allowed.

1.

PERFORM list1, list2.

You will meet with this syntax error below.

Instead you should use PERFORM: list1, list2. instead.


To exchange the content of two INTEGER variables in ABAP without
intermediate variable, it could be implemented like below:

DATA: A TYPE INT4 VALUE 3,


B TYPE INT4 VALUE 2.
A = A + B.
B = A - B.
A = A - B.
WRITE: A, B.

6. Dynamically change inheritance relationship in the runtime


In ABAP once a class is assigned with a super class, this parent-child
relationship could not be changed in the runtime. However for Javascript,
since the OO concept is implemented differently, this relationship did allow
change in the runtime.
Suppose we have defined a class Employee which owns two sub class
OracleEmployee and SAPEmployee. The both subclass have been inherited
from Employee by making their prototype attribute pointing to
Employee.prototype( line 21 and 22 ), and in their constructor, explicitly call
the parent's constructor via the keyword call which is explained in example
1. Both sub class can use the function displayName since it is inherited from
Employee.prototype.
<html>
</html>
<script>
function Employee(name, language) {
this.name = name;
this.language = language;
this.company = "";
}
Employee.prototype.displayName = function() {
console.log("My name is: " + this.name, " I am good at " + this.language + " and currently work at "
+ this.company );
}
function SAPEmployee(name, language) {
Employee.call(this, name, language);
this.company = "SAP";
}
function OracleEmployee(name, language) {
Employee.call(this, name, language);
this.company = "Oracle";
}
SAPEmployee.prototype = Object.create(Employee.prototype);
OracleEmployee.prototype = Object.create(Employee.prototype);
var iTom = new OracleEmployee("Tom", "Java");
iTom.displayName();
console.log( "Is Tom working at Oracle? " + ( iTom instanceof OracleEmployee ));

Execute the script and we could have expected output:


My name is: Tom I am good at Java and currently work at Oracle

Is Tom working at Oracle? true

Now let's append several lines below:


OracleEmployee.prototype = SAPEmployee.prototype;
OracleEmployee.prototype.constructor = SAPEmployee;
var iJerry = new OracleEmployee("Jerry", "Java");
console.log( "Is Jerry working at SAP? " + ( iJerry instanceof SAPEmployee ));
Now although the instance iJerry is initialized via constructor
OracleEmployee, however since the prototype attribute of it has been
modified to point to SAPEmployee, so in this case iJerry instanceof
SAPEmployee will return true.
Output in Chrome console:
My name is: Tom I am good at Java and currently work at Oracle
Is Tom working at Oracle? true
Is Jerry working at SAP? true
This could be observed in Chrome debugger, in this case the parent of
instance iJerry is actually changed to class SAPEmployee instead.

7. argument passing logic


Let's borrow the "optional parameter" terminology from ABAP. In Javascript
all parameters defined in function are optional. See example below, when
you use the Developer constructor function, you can decide which
parameters should be passed.
<html>
<script>
function Developer(name, language, year) {

this.name = name;
this.language = language;
this.year = year;
}
var iJerry = new Developer("Jerry", "ABAP", "7");
var iTom = new Developer("Tom", "Java");
var iBob = new Developer("Bob");
</script>
</html>

Execute the code using Chrome debugger. Then we can observe from
debugger that if a given parameter is not specified during function call, the
corresponding field inside the Developer will hold an uninitialized value "undefined."

built-in array Arguments in Javascript


From example 3 we could also find there is a built-in array named
arguments which could be used to get all parameters passed inside the
function.

Dynamic parameter passing in ABAP


And for ABAP, if we would like a given function module to have the same
behavior regarding the parameter pass, we have to explicitly mark the
parameter as optional

Inside the function module, we can use keyword IS_SUPPLIED to check


whether a given parameter is specified during call.

FUNCTION ZABAP_FM_ARGUMENT.
WRITE: / 'Para1:', iv_para1.
WRITE: / 'Para2:', iv_para2.
WRITE: / 'Para3:', iv_para3.
WRITE: / 'Para4:', iv_para4.
IF iv_para1 IS SUPPLIED.

WRITE: / 'iv_para1 supplied.'.


ENDIF.
IF iv_para2 IS SUPPLIED.
WRITE: / 'iv_para2 supplied.'.
ENDIF.
IF iv_para3 IS SUPPLIED.
WRITE: / 'iv_para3 supplied.'.
ENDIF.
IF iv_para4 IS SUPPLIED.
WRITE: / 'iv_para4 supplied.'.
ENDIF.
ENDFUNCTION.

IF we go a further step, suppose in the design time, we don't know which


parameter will be used, for example if end user choose the checkbox for p2
and p3, which means parameter iv_para2 and parameter iv_para3 will be
passed into with integer value 2 and 3.
In order to fulfill this dynamic pass behavior, we can leverage the keyword
CALL FUNCTION func PARAMETER-TABLE para_ptab. See source code below:

REPORT zpara_test.
PARAMETERS: p1 AS CHECKBOX,
p2 AS CHECKBOX,
p3 AS CHECKBOX,
p4 AS CHECKBOX.
DATA: lt_ptab TYPE abap_func_parmbind_tab,
ls_ptab1 LIKE LINE OF lt_ptab,
ls_ptab2 LIKE LINE OF lt_ptab,
ls_ptab3 LIKE LINE OF lt_ptab,
ls_ptab4 LIKE LINE OF lt_ptab,
lv_para1 TYPE int4 VALUE 1,
lv_para2 TYPE int4 VALUE 2,
lv_para3 TYPE int4 VALUE 3,
lv_para4 TYPE int4 VALUE 4,
start-of-selection.
IF p1 = 'X'.
ls_ptab1-name = 'IV_PARA1'.
ls_ptab1-kind = abap_func_exporting.
GET REFERENCE OF lv_para1 INTO ls_ptab1-value.
APPEND ls_ptab1 TO lt_ptab.
ENDIF.
IF p2 = 'X'.
ls_ptab2-name = 'IV_PARA2'.
ls_ptab2-kind = abap_func_exporting.

GET REFERENCE OF lv_para2 INTO ls_ptab2-value.


APPEND ls_ptab2 TO lt_ptab.
ENDIF.
IF p3 = 'X'.
ls_ptab3-name = 'IV_PARA3'.
ls_ptab3-kind = abap_func_exporting.
GET REFERENCE OF lv_para3 INTO ls_ptab3-value.
APPEND ls_ptab3 TO lt_ptab.
ENDIF.
IF p4 = 'X'.
ls_ptab4-name = 'IV_PARA4'.
ls_ptab4-kind = abap_func_exporting.
GET REFERENCE OF lv_para4 INTO ls_ptab4-value.
APPEND ls_ptab4 TO lt_ptab.
ENDIF.
CALL FUNCTION 'ZABAP_FM_ARGUMENT' PARAMETER-TABLE lt_ptab.

Further discussion on ABAP function module passing approach


For me, during my project which involves SAP system integration with third
party application, it is required that the signature of ABAP function module
must be kept stable but flexible and open for further enhancement. In such
case I will use the "name-value pairs" to hold the importing parameter.
Now the signature has been changed to a table type whose line type is a
structure with two fields: NAME and VALUE.

Now inside the function module I have to evaluate each parameter to check
whether it is passed in by myself:

FUNCTION ZABAP_FM_ARGUMENT1.
DATA: ls_para like line of it_para.
LOOP AT it_para INTO ls_para.
CASE ls_para-name.
WHEN 'IV_PARA1'.

WRITE: / 'Para 1 is
WHEN 'IV_PARA2'.
WRITE: / 'Para 2 is
WHEN 'IV_PARA3'.
WRITE: / 'Para 3 is
WHEN 'IV_PARA4'.
WRITE: / 'Para 4 is
ENDCASE.
ENDLOOP.
ENDFUNCTION.

supplied, value: ' , ls_para-value.


supplied, value: ' , ls_para-value.
supplied, value: ' , ls_para-value.
supplied, value: ' , ls_para-value.

In this case the dynamic call will be changed as below:

REPORT zpara_test.
PARAMETERS: p1 AS CHECKBOX,
p2 AS CHECKBOX,
p3 AS CHECKBOX,
p4 AS CHECKBOX.
DATA: ls_nv_pair TYPE CRM_IC_NAME_VALUE,
lt_nv_pair TYPE CRM_IC_NAME_VALUE_TA.
start-of-selection.
IF p1 = 'X'.
ls_nv_pair-name = 'IV_PARA1'.
ls_nv_pair-value = 1.
APPEND ls_nv_pair TO lt_nv_pair.
ENDIF.
IF p2 = 'X'.
ls_nv_pair-name = 'IV_PARA2'.
ls_nv_pair-value = 2.
APPEND ls_nv_pair TO lt_nv_pair.
ENDIF.
IF p3 = 'X'.
ls_nv_pair-name = 'IV_PARA3'.
ls_nv_pair-value = 3.
APPEND ls_nv_pair TO lt_nv_pair.
ENDIF.
IF p4 = 'X'.
ls_nv_pair-name = 'IV_PARA4'.
ls_nv_pair-value = 4.
APPEND ls_nv_pair TO lt_nv_pair.
ENDIF.
CALL FUNCTION 'ZABAP_FM_ARGUMENT1'
EXPORTING
it_para = lt_nv_pair.

By using this name-value pair, next time if the thrid party application asks
the SAP application to support some new parameter, there is no need to
change the current signature - new supported parameter could still be
passed in as name value pair, and just a new WHEN branch needs to be
added in function module body.
8. predefined data type and wrapper object if any

There are lots of predefined types in ABAP which you could find a complete
list from ABAP help.

In ABAP, you could not create an object instance based on a predefined ABAP
type via key word CREATE OBJECT as below:
DATA: lv_integer TYPE REF TO int4.
CREATE OBJECT lv_integer.

You will receive syntax error "LV_INTEGER" is not an object reference. It is


only possible to create data reference via CREATE DATA.
In Javascript, most predefined data type ( except null and undefined ) like
Number, String and Boolean have their corresponding wrapper object. Open
your Chrome, launch development tool via F12 and do the test below.
Type 1.toString() in console and you will get syntax error, since 1 is not an
object instance, so it is wrong to try to perform the object method toString.

if you change to (1), then the method execution works, because by using
"()", an instance of wrapper object of type Number is created implicitly.

Actually (1).toString() equals to the last two lines below:

9. me in ABAP VS this in Javascript


Let me reuse the definition on "me" in ABAP help: within the implementation
of every instance method, an implicitly created local reference variable
called me is available, which points to the instance in which the method is
currently being executed. me is treated like a local constant, that means the
value of me cannot be altered in an instance method.
The example below shows the me reference is protected inside the instance
method:

although you could use the code below to pass the syntax check,

still it will end up with runtime error:

The example below shows "me" is reserved word in ABAP and could not be
used to name attribute, parameter and variable.

If you have ever programmed using C++, C# and Java, the usage of "this" is not new to you. However
since Javascriot does not have built-in support for class concept, there is still some difference of "this"
usage. Consider the following code:
<script>
function Person(first_name, family_name) {

this.first_name = first_name;
this.family_name = family_name;
this.introduce = function() {
console.log("Hello everyone, I am " + this.first_name + " , " + this.family_name );
}
}
var person = new Person("Jerry", "Wang");
person.introduce();
var func = person.introduce;
func();
</script>

Firstly we call instance method "introduce" via the object reference person,
and works as expectedly. Secondly I pass the "introduce" method of person
reference to another variable func. This time both name are printed as
"undefined".
Hello everyone, I am Jerry, Wang
Hello everyone, I am undefined, undefined
We could find root cause in debugger. When "introduce" method is called
through variable func, in the runtime "this" does not hold the reference of
variable person, but points to global object Window instead. Since both
attributes "first_name" and "family_name" do not exist in Window, we get
"undefined" printed.

So the rule is, when a method ( to be more exactly, a function ) is called via
the approach <object_reference>.<method>, inside the method execution,
"this" will be set as <object_reference> by runtime. In other cases, "this" will
point to the global variable Window.
It is known that any variable defined outside functions will become as an
attribute in global variable Window.
We could verify this rule by adding two lines below:

var first_name = "Thomas";


var family_name = "Zhang";
var func = person.introduce;
func();

And we can see two new attributes in Window variable in debugger:

And the introduce method actually prints the name from Window this time.
Hello everyone, I am Jerry, Wang
Hello everyone, I am Thomas, Zhang
There is another way which could achieve the same result to get Thomas,
Zhang printed:

var person = new Person("Jerry", "Wang");


var person2 = new Person("Thomas", "Zhang");
person.introduce();
var func = person.introduce.bind(person2);
func();

Using bind method, we could really specify an object reference which will be
treated as "this" when the function who call "bind" is executed in the
runtime.

Você também pode gostar