JavaScript中System.import嵌套调用后addMessages方法无法访问求助
解决System.import加载模块后调用addMessages失败的问题
问题根源
- 未接收
frm/mod/messages模块的导出对象,导致无法访问其内部的addMessages方法 - 调用时方法名拼写错误:
addMEssages应为addMessages(注意字母大小写) - 嵌套的
System.import写法不仅低效,还容易引发作用域访问问题
解决方案
方案1:修正拼写并正确接收模块导出
先修正方法名拼写错误,同时在加载messages模块时接收其导出对象,确保方法在作用域内可访问:
System.import("frm/core").then(function(core) { // 接收messages模块的导出对象 System.import("frm/mod/messages").then(function(messages) { core.companionScript("something", function ($element, options) { "use strict"; function doSomething(password){ // ... if(condition) { // 通过导出对象调用正确命名的方法 messages.addMessages("p1", "p2", {errors : ["errKEy"]}); } // ... } }); }); });
方案2:用Promise.all并行加载模块(更优)
由于两个模块无依赖关系,无需嵌套加载,用Promise.all同时加载可提升效率,还能避免嵌套作用域问题:
Promise.all([ System.import("frm/core"), System.import("frm/mod/messages") ]).then(function([core, messages]) { core.companionScript("something", function ($element, options) { "use strict"; function doSomething(password){ // ... if(condition) { messages.addMessages("p1", "p2", {errors : ["errKEy"]}); } // ... } }); });
额外提示
如果addMessages是模块挂载到全局对象的方法,需确保模块加载完成后再调用,但这种方式不推荐——更规范的做法是通过模块导出获取方法,避免全局作用域污染。
内容的提问来源于stack exchange,提问作者Andrej Flieger
相关产品推荐
相关产品推荐

