使用IIFE功能以外的功能

时间:2017-06-12 13:44:24

标签: 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') {
        // 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功能之外访问或调用这些功能的最佳解决方案是什么?

提前致谢。

1 个答案:

答案 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')