Quantcast
Channel: SCN : Document List - ABAP Development
Viewing all articles
Browse latest Browse all 935

A list of Javascript interesting features compared with ABAP

$
0
0


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.

 

<html><script>
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);</script></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

 

clipboard1.png

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.


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

 

clipboard3.png

Finally it generates output like below:

clipboard4.png

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').


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


clipboard6.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:

 

clipboard7.png

4. Constructor redefinition

 

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

 

clipboard8.png

clipboard9.png

 

However in Javascript, it is allowed to redefine a function implemention inside itself, sounds crazy?

 

Let's first have a look at this small piece of code:

 

 

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

 

 

it pops up No, since we use "===" comparator and person1 and person2 are two different object instance.

 

clipboard10.png

 

Now inside function Person, I overwrite it by just return the buffered "this" instance, so all the subsequence call of new Person will always return that bufferred 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:

clipboard11.png

with the help of the so called comma expression, some interesting requirement could be filfilled.

For example, there is a famous interview question: how to exchange the content of two 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>

 

 

clipboard12.png


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


PERFORM list1, list2.


You will meet with this syntax error below.

clipboard13.png

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.

 

clipboard14.png

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.

 

clipboard15.png


This could be observed in Chrome debugger, in this case the parent of instance iJerry is actually changed to class SAPEmployee instead.

clipboard16.png

I will keep updating this document once new comparisons between Javascript and ABAP have been found.list


Viewing all articles
Browse latest Browse all 935

Trending Articles