For every Fiori application we have Component.js, and there is a function extend() call. See one example below.What is the purpose of this function call and what functionality would it achieve?
In order to understand the logic of extend, it is necessary to understand prototype concept in JavaScript. Let’s have a look at some more simple example.
See this simple html source code:
I use prototype inheritance to achieve the class inheritance logic which is commonly used in other language like Java.
cat instanceof Animal and cat instanceof Cat both return true as expected.
There are two flaws of this inheritance solution:
(1) every variable created by function constructor has one attribute proto, which points to the prototype object of its constructor. This could be verified by the fact that statement “cat.proto === Cat.prototype ” returns true.
In this example, you can find there are actually duplicate attribute sName, one in cat itself and the other one in its prototype.
(2) in above code line 17, I try to build the inheritance relationship from Animal to Cat. Here a new instance of Animal is created. Suppose in productive code if we have a complex implementation of Animal, this initialization could consume unnecessary resource and memory to finish.
So another approach is used:
Both flaws in first approach are avoided:
(1) No duplicate attribute “sName” in prototype chain now.
(2) The initialization of a new instance of Animal when trying to build prototype chain is avoided. Instead here I use a very light weighted, dummy function as a bridge to connect Animal and Cat. The trick is done among lines 5 ~ 8 below. Once done, every variable created by constructor Cat has its proto points to Animal.
Now we have already enough knowledge to understand the extend() call done in Componnet.js in Fiori application.
(1) extend call will call Metadata.createClass.
(2) In Metadata.createClass, the essential idea of line 333 is just exactly the same as the code in my second prototype inheritance approach:
function dummy() {};
dummy.prototype = parent.prototype;
this.prototype = new dummy();
Now when I enter the context of my application, I can get the instance of this component via this(controller reference).getOwnerComponent().
From the belowing two test statement in console, I can ensure that the prototype chain is built:
(1) ownComponent.proto.proto.constructor === sap.ca.scfld.md.ComponentBase returns true
(2) ownComponent.hasOwnProperty(“getMetadata”) returns false and ownComponent.proto.proto.hasOwnProperty(“getMetadata”) returns true.