javascript - 如何将javascript函数导出为模块
问题描述
我已经导出了一个函数并在 Javascript 中导入了它,但我可以访问其中的函数的唯一方法是像这样键入它:
myModule.mainFunc().func1()
但我想要实现的更像是这样的:
myModule.mainFunc.func1()
目前,如果我尝试像这样引用它,它会给出错误。
我尝试将函数的值作为对象返回,但它仍然需要我将其作为函数调用。
function greet() {
var hello = () => {
console.log("hello there");
};
var hi = () => {
console.log("hi there");
};
return { hello: hello, hi: hi }; // I've tried this doing it like this
}
export default {greet};
这是我导入它的方式:
import greetings from "./index.js";
greetings.greet().hello()
解决方案
您不能将函数内部定义的greet
函数引用为
myModule.mainFunc.func1()
因为它本身myModule.mainFunc
就是一个greet
函数。您要导入的是调用greet
函数的结果。
您可以greet
通过将函数设为IIFE (Immediately Invoked Function Expression)
. 这样做将在定义函数后立即执行该函数。
const greet = (function() {
var hello = () => {
console.log("hello there");
};
var hi = () => {
console.log("hi there");
};
return { hello, hi };
})();
export default { greet };
现在当你导出时greet
,你不是导出greet
函数,而是调用greet
函数的结果,它是一个有两个函数的对象,hello
和hi
。
推荐阅读
- c# - 有没有办法中止一个线程,然后用一个新变量再次打开它?
- asp.net - 如何在不使用 jsoup 的情况下从 asp.net 页面获取数据到 android 应用程序?
- sql - 如何在 where 子句 [BigQuery] 中为数组设置条件
- c# - 如何使用另一个表单中的 ArrayList 填充组合框?
- opencv - 从内存中释放 OpenCV Mat
- google-data-studio - Google Data Studio 中字符串/数字数组的字段?
- javascript - 图像未在打印预览中呈现
- java - 如何解决数组列表中未知来源的问题?
- tableau-api - 如何使 View 更小 Tableau?
- sapui5 - 如何将项目添加到 JSONModel