SAP UI5 中的函数声明

问题描述

我是 UI5 的初学者,我找不到以下问题的答案: 为什么在 UI5 函数中是这样声明的:

Right way

我不能这样声明:

Wrong way

我找不到任何显示一个图片函数声明的 JavaScript 资源。 谢谢

解决方法

这就是 JS 的工作方式。一切都可以被一切引用。最佳做法是将函数组织到对象中。 extend 方法最终返回一个对象。

我建议您在将 esLint 规则 func-style 设置为 expression 的情况下禁止正常声明。

我把每一个组合都放在一个例子中

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()
,

你可以以任何你想要的方式声明一个函数,但通常,在 sapui5 中,我们扩展了一些控制并在其中编写代码,所以当你在类或对象中声明一个函数时,正确的声明方式是

{
   demo : function(){
   }
}

不是

{
   function demo(){
   }
}