function declaration in SAP UI5

1.2k Views Asked by At

I'm a beginner to UI5 and I couldn't find an answer to the following question: Why in UI5 functions are declared this way: Right way

and I can't declare it this way: Wrong way

I couldn't find any JavaScript resource that shows the first picture function declaration . thanks

2

There are 2 best solutions below

0
user2524011 On

you can declare a function any way you wish, but usually, in sapui5 we extend some control and we write code inside it so when you declare a function inside a class or object right way to declare is

{
   demo : function(){
   }
}

not

{
   function demo(){
   }
}
0
Benedikt Kromer On

This is how JS works. Everything can be referenced by everything. It is best practise to organise functions into objects. The extend method returns in the end an object.

I recommend you to disallow normal declaration with the esLint rule func-style set to expression.

I put every combination into an example

sap.ui.define([ "...BaseController", "sap/base/Log" ], function( BaseController, Log
) {
    "use strict";
    // "normal function definition", exists within the outer {}
    function normal(){  }
    // function expression, exists within the outer {}
    const functionExpression = function(){  };

    // this is basically: return { onInit : ()=>{}, ... }
    return BaseController.extend("controller.Detail", {
        onInit: function() {
            // constructor call
            BaseController.prototype.onInit.apply(this, arguments);
            // extend makes sure that 'this' points to the controller
            this.objectLiteralWithPointerTofunction.call(this);
            // prints 1
            console.log(this.objectLiteralWithBasicIntValue);
        },
        objectLiteralWithBasicIntValue: 1,
        // object literal pointing to a function
        objectLiteralWithPointerTofunction: function(){
           // nested code can access the outer definitions
           normal();
           functionExpression();
           // you can nest as deep as you want
           const functionExpression2 = ()=>{};
        }
    });
});
// you can NOT call anywhere else the nested functions !!!
normal();
functionExpression();
functionExpression2()