2017-06-12 7 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; 
     }; 

})); 

、それは私が何をしたいのか、その後、自動的に起動しますが、別のJavaScriptファイルは、このメソッドを使用することです。

b.isValid('value to test'); 

これは可能ですか?または、このIIFE関数の外部からこれらの関数にアクセスしたり、これらの関数を呼び出すための最良のソリューションはどのようにありますか?

ありがとうございます。

あなたはその後、 exportsオブジェクトまたはルート(または何でも)に割り当てられてしまいますファクトリ関数からいくつかの値を返すことができ
+0

あなたは窓 'にそれを割り当てることができ[ 'B']' IIFEの外部の変数に戻しますか? –

+0

UMDは偶然にのみ使用していますか? – Bergi

+0

ちょうど同じパターンを使用すると、魔法のように動作します。メソッドをインポートした後、グローバル 'b'モジュールにメソッドを追加しています。まったく同じ方法で他のファイルにメソッドをインポートすることができます。 – Bergi

答えて

-1

...

例えば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') 
関連する問題