-2

I read below codes and try to understand keyword this refer to which object.

 sap.ui.define([
   "sap/ui/core/mvc/Controller",
   "sap/m/MessageToast",
   "sap/ui/model/json/JSONModel"
], function (Controller, MessageToast, JSONModel) {
   "use strict";
   return Controller.extend("myAppAddress.controller.App", {
      onInit : function () {
         // set data model on view
         var oData = {
            recipient : {
                name : "World"
            }
         };
         var oModel = new JSONModel(oData);
         this.getView().setModel(oModel);
      },
      onShowHello : function () {
         MessageToast.show("Hello World");
      }
   });
});

enter image description here

As my understanding, this should refer to the extended controller "myAppAddress.controller.App". As the attached debugger screenshot I checked, this itself does not contain the methods onInit and onShowHello, but at its upper level. What is wrong of my understanding? Thanks in advance if someone can give the answer.

sisi
  • 7
  • 3
  • you call "this" inside the onInit() function.. so "this" only knows what it's inside here.. in case you want to extend your "this" you need to change this onInit into a arrow function – CrissCrossCrass Apr 04 '22 at 19:40
  • Thanks for reply. But as the concept, the keyword "this" inside a function always refers to the object who calls this function. so in this case, the object should be my extended class: myAppAddress.controller.App. I mean "this" should know who called it... – sisi Apr 04 '22 at 19:50
  • 1
    "`this` should refer to the extended controller "myAppAddress.controller.App".*" - no, it'll refer to the *instance* of the app controller class that the method was called on. "*this itself does not contain the methods onInit and onShowHello, but at its upper level.*" - that's standard prototypical inheritance. – Bergi Apr 04 '22 at 21:26

1 Answers1

0

First, as per your comment, this does not always refer to the object that calls the function. It can be changed in many ways. It refers to the context that the function runs in, which often is the calling object but that's no guarantee at all. Here that is correct but I felt I should point it out.

Second, the extend keyword in Controller.extend does not extend the Object, it extends the class prototype. _oView is a property of your controller object, but onInit is a function on the prototype. Because your object is also an instantiated class, it receives all the methods associated with the class through the prototype.

The local section you're looking at in the debugger refers only to the variables in current local scope, which include the generic this, and the variables oData and oModel, because you created those in local scope. They are not part of the object but you can use them while building your onInit function.

These are call concepts of JavaScript that are worth looking into

Jorg
  • 7,219
  • 3
  • 44
  • 65