Pass a variable from one IIFE to another

淺唱寂寞╮ 提交于 2019-12-11 01:36:17

问题


I have an index.html file like this and several .js and .css files. What I would like is to make the two .js files communicate with each other, I want to pass variables from one file to another.

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...

}());

What I want is pass variables aToPass and firstToPass (of a.js) to b.js file. How can I do that?

I used the IIFE approach to split the code into several files but if there is a better way, I am willing to change the code structure.


回答1:


You can pass an instance of the object to b.

In your b anonymous function...

(function b(MODULE) {

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

    // other code...

})(MODULE);



回答2:


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;

and 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...
    })();


来源:https://stackoverflow.com/questions/50523604/pass-a-variable-from-one-iife-to-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!