简体   繁体   中英

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. 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. 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. (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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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