user3350003 user3350003 - 2 months ago 13
Javascript Question

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>




Answer

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