我在NodeJS/JavaScript中跟踪任务时遇到了麻烦。 我有多个模块,根据情况将被导入(module1,module2,module3)。 我已经设法使用var language=require(variable+'path')
动态地导入了它们。问题是要使用的函数也应该是动态的,并且不是相同的,因此有时我需要从module1中“创建”函数,但有时我可能需要“更新”函数而不是“创建”函数。 我试图在一个变量上使用create/update(选项取决于任务),但是使用language.variable是行不通的,因为它假定“variable”是模块中函数的名称(我猜)。
这可能吗/有人有可能的解决办法吗?
function haveThisClassFunctionX(classInstance, functionName) {
return Object.getOwnPropertyNames(classInstance)
.concat(Object.getOwnPropertyNames(classInstance.__proto__))
.filter(item => typeof classInstance[item] === 'function')
.some(v => v === functionName);
}
class DeutschModule {
constructor() {
this.language = 'de';
}
create() {
return this.language;
}
}
class EnglishModule {
constructor() {
this.language = 'en';
}
create() {
return this.language;
}
update() {
return this.language;
}
}
const languages = [
new DeutschModule(),
new EnglishModule(),
];
for (const lang of languages) {
console.log(lang.constructor.name);
console.log('has create: ' + haveThisClassFunctionX(lang, 'create'));
console.log('has update: ' + haveThisClassFunctionX(lang, 'update'));
}