Javascript 使用IIFE函数之外的函数
我有以下方法,它位于someFile.js中:Javascript 使用IIFE函数之外的函数,javascript,function,iife,Javascript,Function,Iife,我有以下方法,它位于someFile.js中: (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['b'], factory); } else if (typeof exports === 'object') { /
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['b'], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require('b'));
} else {
// Browser globals (root is window)
root.returnExports = factory(root.b);
}
}(this, function (b) {
//use b in some fashion.
// Just return a value to define the module export.
// This example returns an object, but the module
// can return a function as the exported value.
b.isValid = function(parameter){
if (!isString(parameter)){
return false;
}
parameter = this.newFormat(parameter);
return parameter;
};
}));
作为一个IIFE函数,它将自动调用自身,但我想在一个单独的JavaScript文件中使用该方法,类似于:
b.isValid('value to test');
这可能吗?或者,从IIFE函数外部访问或调用这些函数的最佳解决方案是什么
提前感谢。您可以从factory函数返回一些值,然后将这些值分配给导出的
对象或根(或任何对象)
例如,module.js
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['dependency'], factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require('dependency'));
} else {
// Browser globals (root is window)
root['identifier']= factory(root['dependency']);
}
})(this, function (dep) {
// Just return a value to define the module export.
// This example returns an object, but the module
// can return a function as the exported value.
return {
fn: function(){
console.log([].slice.call(arguments))
}
}
});
index.html
<script src="module.js"></script>
<!-- Module will be executed in the global context and it's value will be assigned to the window object -->
<script>
// can access the module's export here
window['identifier'].fn('something', 'goes', 'here')
// or, preferred way would be: identifier.fn('something', 'goes', 'here')
</script>
您可以将其分配到窗口['b']
或将其返回到生命之外的变量?您使用UMD只是出于偶然吗?只需使用完全相同的模式,它就会神奇地工作。导入后,您正在向全局b
模块添加一个方法,您可以以完全相同的方式将其导入其他文件中。我认为以这种方式变异(或扩展)依赖项不是一个好主意(除非b
是某个库,module
是某个插件或类似的东西)
// CommonJS
var depX = require("./module.js") // can omit .js extension
depX.fn('something', 'goes', 'here')
// es6
import depX from "./module.js" // can omit .js extension
depX.fn('something', 'goes', 'here')