base.html
文件中有一些逻辑。我想简化其对应的js
文件,并保留一些功能。
是否可以从另一个main.js
访问一个IIFE(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);
})();
这个solution给我未定义的内容。
答案 0 :(得分:2)
如果将其转换为js模块,就可以做到。
var mainModule = (function(){
var test = 123;
return {
getTest: function() { return test;}
}
})();
然后在extra.js中
mainModule.getTest();
答案 1 :(得分:1)
在函数内部定义的变量仅在该函数中具有作用域,而不能在外部访问。
您可以全局声明变量test
答案 2 :(得分:1)
一种方法是在外部声明变量,并使它成为全局变量,以供其他函数访问。
var test;
(function(){
test = 123;
})();
现在,何时
(function(){
alert(test);
})();
运行test
在范围内,因此可以访问。但是,该订单需要维护,否则测试将为undefined
,因为尚未定义。
答案 3 :(得分:1)
在功能级别范围内的变量不能在外部访问。可以在外部定义变量,也可以将其添加到window对象中以进行访问。
(function(){
window.test = 123;
})();
(function(){
alert(test);
})();