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.

function ABAPDeveloper(name, year)
{
  this.name = name;
  this.year = year;
  this.codeABAP = function() {
  console.log("Hello, my name is: " + this.name + " I have " + this.year
  + " year's ABAP development experience");
  }
}
function CDeveloper(name, year, os)
{
  this.name = name;
  this.year = year;
  this.os = os;
  this.codeC = function() {
  console.log("Hello, my name is: " + this.name + " I have " + this.year
  + " year's C development experience focus on " + os + " system.");
  }
}
var iJerry = new ABAPDeveloper("Jerry", 7);
iJerry.codeABAP();
var iTom = new CDeveloper("Tom", 20, "Linux");
iTom.codeC();
iTom.codeC.call(iJerry);

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.

/wp-content/uploads/2014/07/clipboard2_496250.png

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”,

<html>
<p>hello</p>
<script>
function a() { console.log("I am function a");}
function b() { console.log("I am function b");}
var d = a;
var e = b;
a();
b();
d();
e();
(function(name) { console.log("I am function: " + name); })("c");
</script>
</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.

/wp-content/uploads/2014/07/clipboard3_496251.png

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:

DATA itab TYPE TABLE OF string.
DATA prog  TYPE string.
DATA class TYPE string.
DATA oref TYPE REF TO object.
APPEND `program.`                     TO itab.
APPEND `class main definition.`       TO itab.
APPEND `  public section.`            TO itab.
APPEND `    methods meth.`            TO itab.
APPEND `endclass.`                    TO itab.
APPEND `class main implementation.`   TO itab.
APPEND `  method meth.`               TO itab.
APPEND `    message 'Test' type 'I'.` TO itab.
APPEND `  endmethod.`                 TO itab.
APPEND `endclass.`                    TO itab.
GENERATE SUBROUTINE POOL itab NAME prog.
class = `\PROGRAM=` && prog && `\CLASS=MAIN`.
CREATE OBJECT oref TYPE (class).
CALL METHOD oref->('METH').

/wp-content/uploads/2014/07/clipboard5_496253.png

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.

/wp-content/uploads/2014/07/clipboard6_496254.png

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:

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

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

/wp-content/uploads/2014/07/clipboard7_496255.png

4. Constructor redefinition

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

/wp-content/uploads/2014/07/clipboard8_496256.png

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:

function Person(name)
{
    this.name = name;
}
var person1 = new Person("Jerry");
var person2 = new Person("Jerry");
alert( person1 === person2 ? "Yes":"No");

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:

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:

var a =1,b=2;
a=[b,b=a][0];
console.log("a:" + a);
console.log("b:" + b);

a : 2

b : 1

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

PERFORM list1, list2.

You will meet with this syntax error below.

/wp-content/uploads/2014/07/clipboard13_496261.png

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.

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.

/wp-content/uploads/2014/07/clipboard16_496264.png

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.

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");

clipboard7A1.pngclipboard7A2.pngclipboard7A3.png

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.

clipboard7A4.png

clipboard7A5.png

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

clipboard7A6.png

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.

clipboard7A7.png

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 supplied, value: ' , ls_para-value.
  WHEN 'IV_PARA2'.
   WRITE: / 'Para 2 is supplied, value: ' , ls_para-value.
  WHEN 'IV_PARA3'.
   WRITE: / 'Para 3 is supplied, value: ' , ls_para-value.
  WHEN 'IV_PARA4'.
   WRITE: / 'Para 4 is supplied, value: ' , ls_para-value.
 ENDCASE.
ENDLOOP.
ENDFUNCTION.

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 third 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.

/wp-content/uploads/2014/07/clipboardb1_529227.png

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.

/wp-content/uploads/2014/07/clipboardb2_529228.png

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

/wp-content/uploads/2014/07/clipboardb3_529250.png

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

/wp-content/uploads/2014/07/clipboardb4_529251.png

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:

/wp-content/uploads/2014/07/clipboard9a_530972.png

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

/wp-content/uploads/2014/07/clipboard9b_530973.png

still it will end up with runtime error:

/wp-content/uploads/2014/07/clipboard9c_530975.png

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

/wp-content/uploads/2014/07/clipboard9d_530976.png

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:
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();

Firstly we call instance method “introduce” via the object reference person, and works as expected. 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.

/wp-content/uploads/2014/07/clipboard9e_530978.png

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:

/wp-content/uploads/2014/07/clipboard9f_530979.png

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.

To report this post you need to login first.

5 Comments

You must be Logged on to comment or reply to a post.

  1. Christian Guenter

    Hi Jerry,

    very interesting.

    Just a hint,

    it seems that in last screenshot in paragraph 5 the essential parts in row 21 are hidden by the syntax error screen.

    Regards Christian

    (0) 
  2. sankara rao bhatta

    HI,

     

    From where do you get the motivation to write this kind of blogs :). More than that you require lot of patience to write everything in detail to make sure that the reader understands it. Nice blog

    thanks,

    sankar.

    (0) 

Leave a Reply