简体   繁体   English

从外部函数调用Javascript立即函数

[英]Javascript immediate function call from external function

I am trying to call the immediate function defined in test1.js on click of the button defined under html file. 我试图在html文件下定义的按钮单击时调用test1.js中定义的立即函数。 It always throws error "test is undefined". 它总是抛出错误“测试未定义”。 I am little bit aware that being a immediate function, it calls immediately, and so it returns the "undefined error". 我有点意识到,作为立即函数,它会立即调用,因此会返回“未定义错误”。 But is there any way I can call the immediate function (access methods, properties, etc.) on click of the button? 但是,单击按钮有什么方法可以调用立即函数(访问方法,属性等)?

Thank you in advance. 先感谢您。

 //test1.js var test = (function(){ alert(window); var tmp = 'hello'; }()); 
 <!DOCTYPE html> <html> <head> </head> <body> <script type="text/javascript" src="test1.js"></script> <input type="button" id="btn1" value="ClickMe!" /> <script type="text/javascript"> var btn = document.getElementById("btn1"); btn.addEventListener("click",fun1,false); function fun1(){ alert(test.tmp); } </script> </body> </html> 

You have to modify your code so that the IIFE returns an object with a tmp property. 您必须修改代码,以便IIFE返回带有tmp属性的对象。 Such as

var test = (function(){
alert(window);
var tmp = 'hello';
return {tmp:tmp};
}());

You need to explicitly return an object containing any data you want made available after you run the IIFE. 在运行IIFE之后,您需要显式返回一个对象,该对象包含想要使之可用的任何数据。 (Just add the return as I did to the snippet below). (只需像我在下面的代码段中那样添加收益)。

 //test1.js var test = (function(){ alert(window); // you need to return any values you want accessible return { tmp: "hello" } }()); 
 <!DOCTYPE html> <html> <head> </head> <body> <script type="text/javascript" src="test1.js"></script> <input type="button" id="btn1" value="ClickMe!" /> <script type="text/javascript"> var btn = document.getElementById("btn1"); btn.addEventListener("click",fun1,false); function fun1(){ alert(test.tmp); } </script> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM