I am new and learning for JavaScript. I am trying to understand the code line UIComponent.prototype.init.apply(this, arguments)
based on JavaScript syntax for below code snippet.
I have read the link for the same question: Prototype & Extend in SAPUI5 (Component.js). The accepted answer there was like this:
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.
Please correct me if it's wrong: here, the parent class refers to is the UIComponent
, right? The overridden method init
is only done for the extended subclass, but the parent class UIComponent
still has its original init
without overriding. But UIComponent.prototype.init.apply
is calling UIComponent.prototype class, which is even the parent class of UIComponent, right? and most importantly, why do it this way?
I add my debug picture to understand this, and prototype chain, but still not clear.
sap.ui.define([
"sap/ui/core/UIComponent",
"sap/ui/model/json/JSONModel",
"sap/ui/model/resource/ResourceModel",
], function (UIComponent, JSONModel, ResourceModel) {
"use strict";
return UIComponent.extend("sap.ui.demo.walkthrough.Component", {
metadata: {
"interfaces": [
"sap.ui.core.IAsyncContentCreation",
],
"rootView": {
"viewName": "sap.ui.demo.walkthrough.view.App",
"type": "XML",
/*"async": true, // implicitly set via the sap.ui.core.IAsyncContentCreation interface*/
"id": "app",
},
},
aaa: function () {
console.log("aaa");
},
init: function () {
// call the init function of the parent
UIComponent.prototype.init.apply(this, arguments);
// set data model
var oData = {
recipient: {
name: "World",
},
};
var oModel = new JSONModel(oData);
this.setModel(oModel);
// set i18n model
var i18nModel = new ResourceModel({
bundleName: "sap.ui.demo.walkthrough.i18n.i18n",
});
this.setModel(i18nModel, "i18n");
},
});
});