2017-06-12 54 views
0

我有以下的方法,它是一種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

你可以把它分配給'窗口[ 'B']'或者將它返回到IIFE之外的變量? –

+0

你是否偶然使用UMD? – Bergi

+0

只需使用完全相同的模式,它會神奇地工作。導入後,您將在全局'b'模塊中添加一個方法,並且可以以完全相同的方式將其導入到其他文件中。 – Bergi

回答

-1

您可以返回從此將獲得分配給exports對象或根(或其他)的工廠函數一定的價值...

例如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')