简体   繁体   中英

How to access variables inside one IIFE from another using templates?

There is some logic in the base.html file. I want to make its correspondent js file simpler and to put some functions aside.

Is there a way to access variables inside one IIFE ( main.js ) from another ( additional.js )?

base.html

<body>
    <script src="main.js"></script>
    {% block extra_scripts %}
    {% endblock %}
</body>

main.js

(function(){
    var test = 123;
})();

extension.html

{% extends "base.html" %}
{% block extra_scripts %}
    <script src="additional.js"></script>   
{% endblock %}

additional.js

(function(){
    alert(test);
})();

This solution gives me undefined.

You can do it if you turn it into js module.

var mainModule = (function(){
    var test = 123;

    return {
       getTest: function() { return test;}
    }
})();

then in additional.js

mainModule.getTest();

The variable defined inside a function has a scope in that function only and cannot be accessed outside .

You can globally declare the variable test

One way would be to declare the variable outside and make it global to be accessible by other functions.

var test;
(function(){
    test = 123;
})();

Now, when

(function(){
    alert(test);
})();

runs test is within the scope and hence accessible. However, the order needs to be maintained, else test will be undefined for it is not yet defined.

variable which is scoped in function level can not be accessed outside. Either define the variable outside or add it to the window object in order to get accessed.

main.js

(function(){
    window.test = 123;
})();

additional.js

(function(){
    alert(test);
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM