如何在有或没有 IIFE 的情况下为 JavaScript 代码命名命名空间

How do I namespace JavaScript code with or without IIFEs?

本文关键字:JavaScript 代码 情况下 命名空间 IIFE      更新时间:2023-09-26

我一直在阅读命名空间、对象文字、IIFE 等,我试图了解以下哪项是命名空间 JavaScript 代码的正确方法?

具有使用 IIFE 的嵌套外部函数的命名空间

let myApp = myApp || {};
myApp.some_var = "someString";
myApp.some_func = (function(){ const some_const = 1;
let some_other_func = function(){
    console.log(some_const);
};
return {
    some_other_func: some_other_func
}
}());
myApp.another_func = (function(){ const another_const = 2;
let another_func = function(){
    myApp.some_func.some_other_func();
};
return {
    another_func: another_func
}
}());

具有不使用 IIFE 的嵌套外部函数的命名空间

let myApp = myApp || {};
myApp.some_var = "someString";
myApp.some_func = function(){ const some_const = 1;
let some_other_func = function(){
    console.log(some_const);
};
return {
    some_other_func: some_other_func
}
};
myApp.another_func = function(){ const another_const = 2;
let another_func = function(){
    myApp.some_func.some_other_func();
};
return {
    another_func: another_func
}
};

具有内部嵌套函数的命名空间

let myApp = (function() { let some_var = "someString";
let some_func = function(){
    const some_const = 1;
    let some_other_func = function(){
        console.log(some_const);
    };
    return {
        some_other_func: some_other_func
    }
};
let another_func = function(){
    const another_const = 2;
    let another_func = function(){
        some_func.some_other_func();
    };
    return {
        another_func: another_func
    }
};
return {
    some_var: some_var,
    some_func: some_func,
    another_func: another_func
}
}());

二氟化函数

let a_func = (function(){ let some_var = "someString"; }());
let some_func = (function(){ const some_const = 1;
let some_other_func = function(){
    console.log(some_const);
};
return {
    some_other_func: some_other_func
}
}(another_func, a_func));
let another_func = (function(){ const another_const = 2;
let another_func = function(){
    some_func.some_other_func();
};
return {
    another_func: another_func
}
}(a_func, some_func));

编辑:在我自己的特定示例中,代码将在节点中运行.js并且"应用程序"将少于500行代码,因此我计划将其全部放在一个文件中。我对不建议使用AMD,CommonJS,Browserify,Webpack,ES6模块等的答案特别感兴趣。

我直言,最好的方法是使用 CommonJS 标准,从您的代码中我可以看到您已经在使用 EcmaScript6,所以最好的方法是使用 ES6 模块。

在我自己的项目中,我使用browserify - 它允许我使用nodejs/CommonJS模块:

// module1.js
exports.foo = function(value) {
  return value + x;
};
exports.CONST = 1;
// module2.js
var m1 = require('module1');
m1.foo();

您提出的所有方法大致相同,我个人喜欢揭示模块模式,并在无法使用 CommonJS 时尝试使用它。我也喜欢在模块的开头移动返回语句,它有助于可读性:

var MyModule = (function() {
  'use strict';
  return {
    foo: foo
  };
  function foo() {
    return 1;
  } 
}());

另一个重要问题是将整个模块代码包含在 IFFE 中,尤其是当您使用 strict mode 并连接 js 文件时。

好吧,这可能不是您问题的答案,但也许它可以帮助您看到更大的图景......