我在名为 test.js 的文件中有一个 IIFE 函数,即
(function mainIIFE() {
"use strict";
var print_name = function(first, last) {
console.log(first + " " + last);
};
}());
我如何在 html 文件中调用 print_name 。在我的脑海里,我有
<head>
<script type="text/javascript" src="test.js"></script>
</head>
and
<script>
new print_name("Bob", "Downs");
</script>
稍后在我的 html 文件中。
但是当我尝试运行时,它无法识别 print_name 函数。
既然你声明了print_name
with var
,它的作用域是 IIFE 的本地范围,因此您无法从外部调用它。您需要分配给window.print_name
使其全球化。
(function mainIIFE() {
"use strict";
window.print_name = function(first, last) {
console.log(first + " " + last);
};
}());
也不清楚你为什么使用new
调用该函数,因为它不填充对象。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)