Reputation: 3956
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.
Upvotes: 0
Views: 1954
Reputation: 2621
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();
Upvotes: 2
Reputation: 30
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.
(function(){
window.test = 123;
})();
(function(){
alert(test);
})();
Upvotes: 1
Reputation: 59232
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.
Upvotes: 1
Reputation: 50291
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
Upvotes: 1