So i learned something new. A lot of frameworks were using the following syntax in their libraries..
(function() {
...
})();
It's fair to say i was going mad trying to figure out why. I mean you put an alert in there and it pops up when the script loads. So why bother with the function? Why not just write your code as we used to - directly in the page?
Well, thanks to this paper, I have discovered why and this note is as much for my future reading as yours :)
Turns out that you can locally scope variables within these anonymous javascript functions which more importantly means you don't screw up global vars that are being used elsewhere. So you can confidently write the following ...
var person = 'steven';
(function() {
var person = 'xavier';
alert("Person 1 " + person);
})();
alert("Person 2 " + person);
... and you will get "Person 1 xavier" and "Person 2 steven" - notably the global variable "person" was redeclared within the scope of the anonymous function and the name changed, but as it was declared with "var" it does not overwrite the global value. If you did NOT use "var" in the function, you would change the value globally. So it works like every other programming language - just a wee bit different in term of syntax :)
No comments:
Post a Comment