从HTML中调用IIFE函数中定义的函数 [英] Calling function defined in an IIFE function from HTML

查看:118
本文介绍了从HTML中调用IIFE函数中定义的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在名为test.js的文件中有一个IIFE函数,即

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);
    };
}());

我如何在HTML文件中调用print_name。在我的脑海中,我有

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>

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

稍后在我的html文件中。

later on in my html file.

但是当我尝试运行时,它不能识别print_name函数。

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

推荐答案

由于您声明 print_name 与 var ,它的范围是IIFE本地的,所以你不能从外面调用它。你需要分配给 window.print_name 使其成为全局的。

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.

这篇关于从HTML中调用IIFE函数中定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆