我正在使用一些 javascript 函数来模拟 require
功能,例如:
// We set up an object that will include all the public modules
// And then a require function which basically just accesses that public module
const modules = {};
function require(moduleName) {
return modules[moduleName];
}
modules['math.js'] = function() {
// hidden implementation details
let incr = x => ++x;
return {
incr,
sum(x,y) { return x+y; }
}
}
为什么需要执行 modules['math.js'] = (function() {...})();
而不仅仅是上面的普通非调用函数调用?
最佳答案
modules["match.js"]
只是一个函数。您可能希望它成为一个对象:
modules["math.js"] = { ... };
但是您将没有可以使用的私有(private)成员或函数!一切都会公开。所以为了解决这个问题,我们创建了一个闭包:
modules["math.js"] = function () {
let priv = 0;
return { ... };
};
这就是我们现在的位置。为了使它成为一个闭包并让 modules["math.js"]
成为我们可以使用的好对象,我们立即调用这个函数:
modules["math.js"] = (function () {
let priv = 0;
return { ... };
})();
现在,modules["math.js"]
是一个具有我们可以使用的成员和方法的对象,并且它有一个名为 priv
的私有(private)本地范围变量,它可以仅供模块使用。
这类似于 ES6 模块,您可以在其中导出一些绑定(bind)到标识符的选定值,并且文件中的其他所有内容都是私有(private)的。
关于javascript - 为什么在以下情况下需要 IIFE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72088914/