I am new to front end programming. When I was learning jQuery I came across this issue. Here is my code:
<script type="text/javascript">
$(document).ready(function(){
var msg ="hi";
$("#test1").click(function(){alert(msg)});
msg ="hello";
$("#test2").click(function(){alert(msg)});
});
</script>
</head>
<body>
<button id="test1">test1</button>
<button id="test2">test2</button>
On running this code, both the alerts prints "hello". I except the first button on clicking should alert with "hi". Why does it behave like this? Is this the right behavior? Is it because of scope constraint?
Lots of mostly correct explanations here but, much to my surprise, no one’s thrown out the key concept here: closure.
Basically what’s happening is when you declare your two functions, the scope they are declared in forms a closure. That means that the variables inside that closure remain available to the functions. In other words:
Then some time passes, and the click events get called. The functions that are attached to the click events still have access to the closure (inside which the value of
msgis “hello”).The traditional way to “capture” a variable’s value inside a closure is to create an “Immediately Invoked Function Expression” (IIFE). Basically you can think of this as creating an entirely new closure that contains the immediate value of a variable. You could re-write your code to use IIFEs like this:
I hope this makes it a little bit clearer what’s happening, and how to get what you’re looking for.