Running JS in a private context
I've been writing Javascript-based extensions for Google Chrome, which manipulates the information on the screen. One important thing that I always neglect the possibility of variable collision. Especially with my *cough* poorly written code *cough*, variables like i, index and count always collide. I've started using my own object for storing functions and variables, but that increased the script size greatly… e.g.
From:
var checkAwesome = "a string"; var awesomeRegex = /[a-z]/; var awesomeFunction = function(){ return checkAwesome.replace(awesomeRegex,"#"); }
To this: (notice the extra jxeeno. in front of every variable?)
var jxeeno = { checkAwesome: "a string", awesomeRegex: /[a-z]/, awesomeFunction: function(){ return jxeeno.checkAwesome.replace(jxeeno.awesomeRegex,"#"); } };
The solution
Instead, we can run everything within a private context to avoid namespace collision!
(function(){ var checkAwesome = "a string"; var awesomeRegex = /[a-z]/; var awesomeFunction = function(){ return checkAwesome.replace(awesomeRegex,"#"); } })(); // Code here can not access variables within the private context // for example: alert(typeof(checkAwesome)); //would prompt "undefined"
Sorry, no match for the embedded content.
Post preview:
Close preview