只需使用arguments
:
require(amd_modules, function() {
console.log("All modules loaded");
// arguments should now be an array of your required modules
// in the same order you required them
});
但是,除非您有充分的理由这样做,否则您可能需要重新考虑设计应用程序的方式——即使在最顶层,您的模块也应该简单且可测试。具有广泛不同数量的依赖项表明您可能正在尝试在回调函数中做很多事情。将每个代码路径分解成自己的模块,然后只切换到您的顶级依赖项。在代码中:
// Instead of this:
require(amd_modules, function() {
console.log("All modules loaded");
if (complex_condition_A) {
var x = arguments[0],
y = arguments[1],
z = arguments[2];
// Do things with x, y and z
}
else if (complex_condition_B) {
var a = arguments[0],
b = arguments[1];
// Do things with a and b
}
else {
// et cetera, et cetera, et cetera
}
});
// Do this instead
var rootModule;
if (complex_condition_A) rootModule = "A";
else if (complex_condition_B) rootModule = "B";
else rootModule = "C";
require(rootModule, function(root) {
// Root has the same API, regardless of which implementation it is
// This might be as simple as an `init` method that does everything
// or as complex as, say Facebook's API, but with different libraries
// loaded depending on the platform the page is loaded on
// (IE vs. Android for example).
});