模块定义和单独模块中的用法

时间:2018-10-19 07:37:47

标签: javascript sapui5

我在SAPUI5和JS上还很陌生。关于模块的定义和用法,我不太了解。这是我的上下文:

我想创建一个使用外部模块对象my.test.comp的组件my.test.comp.Service。 因此,按照最佳做法,我有以下代码:

Service.js:

sap.ui.define([
  "sap/ui/base/Object"
], function(BaseObject) {
  "use strict";

  var modulePath = jQuery.sap.getModulePath("my.test.comp");
  var SERVICE_ROOT_PATH = modulePath.lastIndexOf("/") > 0
     ? modulePath.substring(0, modulePath.lastIndexOf("/"))
     : "/test";
  var Service = BaseObject.extend("my.test.comp.Service", {
    getServiceRootPath: function () {
      return SERVICE_ROOT_PATH;
    }
  });

  return Service;
});

我在 Component.js中使用它:

sap.ui.define([
  "sap/ui/core/Component",
  "./Service"
], function(Component, Service) {
  "use strict";

  return Component.extend("my.test.comp.Component", {
    init: function() {
      var serviceRootPath = Service.getServiceRootPath();
      jQuery.sap.log.error("ServicePathInfo : " + serviceRootPath);
    }
  });
});

运行此命令时,我收到一条错误消息,提示getServiceRootPath未定义,并引发错误。

因此,我如下更改了 Service.js

sap.ui.define([
  "sap/ui/base/Object"
], function(BaseObject) {
  "use strict";

  var modulePath = jQuery.sap.getModulePath("my.test.comp");
  var SERVICE_ROOT_PATH = modulePath.lastIndexOf("/") > 0
    ? modulePath.substring(0, modulePath.lastIndexOf("/"))
    : "/test";
  var Service = BaseObject.extend("my.test.comp.Service");
  Service.getServiceRootPath = function () {
    return SERVICE_ROOT_PATH;
  };

  return Service;
});

现在它运行良好。我不知道有什么区别。

有人可以解释一下为什么吗?

2 个答案:

答案 0 :(得分:0)

您应该在component.js中导入

“我的/测试/比较/服务”

代替

“。/服务”

答案 1 :(得分:0)

在JS中,没有任何类。无论是普通对象({})还是带有构造函数的函数都可以用new调用。

因此,在UI5中调用.extend("...")会返回一个函数,该函数的构造函数与其他任何函数一样,可以与new一起使用。您的模块成员(方法,属性等)将被添加到 prototype 而不是父函数(Service)本身。

BaseObject.extend("my.test.comp.Service", {
  // methods in prototype ...
});

必需的Service模块(即函数)仅由构造函数(Service.constructor)和 prototype 对象(Service.prototype)组成。这就是在第一种情况下Service.getServiceRootPath未定义的原因。您首先需要使用new调用构造函数:

return Component.extend("my.test.comp.Component", {
  init: function() {
    const service1 = new Service(); /* returns an object with ..
    *  __proto__: {
    *    getServiceRootPath: f ()
    *  }
    */
    const serviceRootPath = service1.getServiceRootPath();
    // ...
  },
});

(您也可以使用Service.prototype.getServiceRootPath而不使用new直接访问该方法)

这也解释了为什么Service.getServiceRootPath在第二种情况下起作用。您可以在现有函数中添加几乎所有您喜欢的东西,因为函数最终也是对象


看起来您的意图不是创建多个“服务”,而是创建一个带有方法的简单对象。在这种情况下,只需在模块定义中返回一个带有方法的简单对象即可。

sap.ui.define([
 // Without "sap/ui/base/Object"
], function() {
  "use strict";
  //...
  return {
    getServiceRootPath: function () {
      // ...
    },
  };
});
sap.ui.define([
  "sap/ui/core/Component",
  "./Service",
], function(Component, Service) {
  "use strict";

  return Component.extend("my.test.comp.Component", {
    init: function() {
      const serviceRootPath = Service.getServiceRootPath();
      // ...
    },
  });
});

这也可以。

相关问题