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

Javascript 单独模块中的模块定义和用法,javascript,sapui5,Javascript,Sapui5,我对SAPUI5和JS很陌生。关于模块的定义和用法,我有些不太理解。以下是我的背景: 我想创建一个使用外部模块对象的组件my.test.comp。 因此,遵循最佳实践,我有以下代码: Service.js: sap.ui.define([ “sap/ui/base/Object” ],函数(BaseObject){ “严格使用”; var modulePath=jQuery.sap.getModulePath(“my.test.comp”); var SERVICE\u ROOT\u PATH=

我对SAPUI5和JS很陌生。关于模块的定义和用法,我有些不太理解。以下是我的背景:

我想创建一个使用外部模块对象的组件
my.test.comp
。 因此,遵循最佳实践,我有以下代码:

Service.js:

sap.ui.define([
“sap/ui/base/Object”
],函数(BaseObject){
“严格使用”;
var modulePath=jQuery.sap.getModulePath(“my.test.comp”);
var SERVICE\u ROOT\u PATH=modulePath.lastIndexOf(“/”)0
?modulePath.子字符串(0,modulePath.lastIndexOf(“/”))
:“/测试”;
var Service=BaseObject.extend(“my.test.comp.Service”{
getServiceRootPath:函数(){
返回服务根路径;
}
});
回程服务;
});
我在组件js:

sap.ui.define([
“sap/ui/core/Component”,
“/服务”
]、功能(组件、服务){
“严格使用”;
返回Component.extend(“my.test.comp.comp.Component”{
init:function(){
var serviceRootPath=Service.getServiceRootPath();
jQuery.sap.log.error(“ServicePathInfo:+serviceRootPath”);
}
});
});
当我运行此命令时,我收到一个错误,说明
getServiceRootPath
未定义,并抛出一个错误

因此,我将Service.js更改如下:

sap.ui.define([
“sap/ui/base/Object”
],函数(BaseObject){
“严格使用”;
var modulePath=jQuery.sap.getModulePath(“my.test.comp”);
var SERVICE\u ROOT\u PATH=modulePath.lastIndexOf(“/”)0
?modulePath.子字符串(0,modulePath.lastIndexOf(“/”))
:“/测试”;
var Service=BaseObject.extend(“my.test.comp.Service”);
Service.getServiceRootPath=函数(){
返回服务根路径;
};
回程服务;
});
现在它运行良好。我不明白有什么不同


有人能解释一下原因吗?

在您的component.js中,您应该导入

“我的/测试/公司/服务”

而不是


“/Service”

在JS中,没有类。可以使用
new
调用普通对象(
{}
)或具有构造函数的函数

因此,在UI5中调用
.extend(“…”)
将返回一个函数,其构造函数与任何其他函数一样,可以与
new
一起使用。您的模块成员(方法、属性等)将添加到原型中,而不是添加到父函数(
服务
)本身

BaseObject.extend(“my.test.comp.Service”{
//原型中的方法。。。
});
所需的
服务
模块(即函数)仅由构造函数(
服务.构造函数
)和原型对象(
服务.原型
)组成。这就是为什么在第一个案例中未定义
Service.getServiceRootPath
。首先需要使用
new
调用构造函数:

返回Component.extend(“my.test.comp.comp.Component”{
init:function(){
const service1=new Service();/*返回带有..的对象。。
*_uu协议_;{
*getServiceRootPath:f()
*  }
*/
const serviceRootPath=service1.getServiceRootPath();
// ...
},
});
(您也可以使用
Service.prototype.getServiceRootPath直接访问该方法,而不使用
new


这也解释了为什么
Service.getServiceRootPath
在第二种情况下工作。您可以向现有函数添加任何您喜欢的内容,因为函数最终也是对象。您好,我想做的是使用第一个服务定义(第一个代码)并在组件中使用它。即使更改依赖项路径,它也会抛出一个错误,表示Service.getServiceRootPath不是函数。请告诉我们其中一个答案是否可以解决此问题!如果有什么不清楚的地方,请随时留言!:)否则,请看