Calling function defined in an IIFE function from HTML

ε祈祈猫儿з 提交于 2019-12-04 07:00:54

问题


I have a IIFE function in a file called test.js i.e.

(function mainIIFE() {
    "use strict";
    var print_name = function(first, last) {
        console.log(first + " " + last);
    };
}());

How would I call print_name in an html file. In my head, I have

  <head>
    <script type="text/javascript" src="test.js"></script>
  </head>

and

<script>
    new print_name("Bob", "Downs");
</script>

later on in my html file.

But when I try to run, it's not recognizing the print_name function.


回答1:


Since you declare print_name with var, its scope is local to the IIFE, so you can't call it from outside there. You need to assign to window.print_name to make it global.

(function mainIIFE() {
    "use strict";
    window.print_name = function(first, last) {
        console.log(first + " " + last);
    };
}());

It's also not clear why you're using new to call the function, since it doesn't fill in an object.




回答2:


You can return the function and store it in a variable. This is essentially the same as assigning it to window.print_name inside the IIFE since the new variable will be in global namespce

var print_name = (function mainIIFE() {
    "use strict";
    var print_name = function(first, last) {
        console.log(first + " " + last);
    };
    return print_name;
}());

print_name('Foo','Bar')


来源:https://stackoverflow.com/questions/47841069/calling-function-defined-in-an-iife-function-from-html

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