Oct 22

This post was written in 2009, please read this stack on why eval is always a bad idea:
https://stackoverflow.com/questions/13167403/is-javascript-eval-so-dangerous</strong>

Usually when I need to call a JavaScript function using a string I use:

function myUsefulFunction() { //useful code }
var foo = 'myUsefulFunction();';
eval(foo);

However a more elegant approach would be to use:

function myUsefulFunction() { //useful code }
this['myUsefulFunction']();


Why does this work? It works because nearly everything in JavaScript is an object, ever tried a for…in object statement in JavaScript? You have probably used this technique 100’s times before when accessing the DOM and had not realised this applies to your own objects too. All you are doing here is using the square bracket notation, using the this keyword to access your function using your function’s name as the identifier.

If you are using complex JavaScript code or libraries you may want to refer to the current execution context, think about it because this is global, someone might extend what this means and give it a different meaning – in our example this[‘myUsefulFunction’] = null; now our code goes bang!

To ensure you know what this means when calling your function use:

function myUsefulFunction() { //useful code }
//Set current execution context, so I know what I am referring to
var currentGlobalContext = this;
//Loads JavaScript maybe calls to other libraries
//I know exactly what myUsefulFunction is being called
currentGlobalContext['myUsefulFunction']();

You can also chain these calls together, the code below uses the same principle, all you are doing is using the function name as the identifier, for example:

function myUsefulFunction() {
//useful code
}
myUsefulFunction.foo = function(){ //more useful code };
//Set current execution context, so I know what I am referring to
var currentGlobalContext = this;
//Loads JavaScript maybe calls to other libraries
//I know exactly what foo function is being called
currentGlobalContext['myUsefulFunction']['foo']();

Of course you can use this too:

function myUsefulFunction() {
//useful code
this.bar = function(){//more useful code}
this.bar.foobar = function(){//even more useful code}
}
myUsefulFunction.prototype.foo = function(){//this is getting boring now!};
var myUsefulObject = new myUsefulFunction();
myUsefulObject['foo']();
myUsefulObject['bar']();
myUsefulObject['bar']['foobar']();

Leave a Reply

preload preload preload