3

I was trying to implement Component.js in my SAPUI5 application but unable to understand .extend & .prototype.init.apply method in below piece of code.

sap.ui.define([
"sap/ui/core/UIComponent"
], function (UIComponent) {
    "use strict";
    return UIComponent.extend(""** , {**
        init: function () {
            UIComponent.prototype.init.apply(this, arguments);
            // console.log(UIComponent.extend);
            UIComponent.prototype.init.apply(this, arguments);
        }
    });
});

Can someone please explain?

P.S. I am beginner to OO Javascript.

Rahul
  • 143
  • 2
  • 16

2 Answers2

5

What they're doing here is very Java-ish. With extend they're creating a subclass of UIComponent.

In this subclass the init method is overridden. When you override a method of the parent object, it's a good practice to call the parents original method from the method that overrides it. By doing so, you're avoiding unexpected situations such as variables that have not been defined at the parent etc. Calling the parent's original method is exactly what the init.apply statement is doing. It's doesn't make sense to me to do this twice though.

jpenninkhof
  • 1,920
  • 1
  • 11
  • 12
2

To give you some hints:

  1. extend comes from from sap.ui.base.Object which delegates to sap.ui.base.ManagedObject.createClass(). Thanks to @schnoedel to point it out.

  2. prototype.init.apply and arguments object.

Community
  • 1
  • 1
Haojie
  • 5,665
  • 1
  • 15
  • 14
  • I think that hints are best given as a comment, not an actual answer – Marc Mar 30 '16 at 06:54
  • 2
    extend does actually not come from jquery but from [sap.ui.base.Object](https://github.com/SAP/openui5/blob/rel-1.34/src/sap.ui.core/src/sap/ui/base/Object.js#L164) which delegates to [sap.ui.base.ManagedObject.createClass()](https://github.com/SAP/openui5/blob/rel-1.34/src/sap.ui.core/src/sap/ui/base/Metadata.js#L301) which does the whole prototype inheritance stuff, creates the properties, associations, aggregations and events from the metadata and much more. – schnoedel Mar 30 '16 at 07:23
  • @schnoedel I just checked and you are right. Thanks a lot. I will edit my answer. – Haojie Mar 30 '16 at 13:48