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"

comments powered by Disqus

Old Comments

Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +

Add a New Comment

Unless otherwise stated, all of the site's contents (including articles, blog post and code snippets) is:
Copyright © Kenneth Tsang 2014