我有以下方法,它位于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') {
// 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功能之外访问或调用这些功能的最佳解决方案是什么?
提前致谢。
答案 0 :(得分:-1)
您可以从工厂函数返回一些值,然后将其分配给exports
对象或根(或其他)......
E.g。 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>
或 some_other_module.js
内// 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')