将变量从一个IIFE传递到另一个IIFE

时间:2018-05-25 07:21:51

标签: javascript iife

我有一个index.html这样的文件以及几个.js.css个文件。 我想要的是让两个.js文件相互通信,我想将变量从一个文件传递到另一个文件。

的index.html

<html lang='en'>
    <head>
        <meta charset='utf-8'>
        <script src='https://d3js.org/d3.v5.js' charset='utf-8'></script>
        <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>  

        <link href='/css/a.css' rel='stylesheet'/>
        <link href='/css/b.css' rel='stylesheet'/>
        <link href='/css/c.css' rel='stylesheet'/>
    </head>

    <body>
        <div id='a'></div>
        <div id='c'></div>
        <div id='b'></div>
    </body>

    <script src='/script/a.js' rel='script'/></script>
    <script src='/script/b.js' rel='script'/></script>
    <script src='/script/c.js' rel='script'/></script>
</html>

a.js

var MODULE = (function a() {

    var my = {};
    my.aToPass = 'a'; // variable to pass at file b.js

    var first = 5;
    var second = 'example';

    function test() {
        my.firstToPass = first + 100; // variable to pass at file b.js
        console.log(first);
    }

    return my;

}());

b.js

(function b() {

    console.log('my:', MODULE.my); // undefined
    console.log('my:', MODULE.aToPass); // undefined
    console.log('my:', MODULE.firstToPass); // undefined

    // other code...

}());

我想要的是将变量aToPassfirstToPassa.js}传递给b.js文件。我怎么能这样做?

我使用IIFE方法将代码分成几个文件,但如果有更好的方法,我愿意改变代码结构。

2 个答案:

答案 0 :(得分:2)

您可以将对象的实例传递给b

b匿名函数中......

(function b(MODULE) {

    console.log('my:', MODULE.my); // undefined
    console.log('my:', MODULE.aToPass); // undefined
    console.log('my:', MODULE.firstToPass); // undefined

    // other code...

})(MODULE);

答案 1 :(得分:-1)

const MODULE = (function () {
      var my = {};

      my.aToPass = 'a'

      var first = 5;
      var second = 'example';

      (function test() {
        my.firstToPass = first + 100; // variable to pass at file b.js

      })();


      return my;
    })();


    module.exports = MODULE;

和b.js:

const MODULE = require('./try');

    (function b() {

      console.log('my:', MODULE.my); // undefined
      console.log('my:', MODULE.aToPass); // my: a
      console.log('my:', MODULE.firstToPass); // my: 105

      // other code...
    })();