call javascript object method with a variable

i am new to object oriented javascript. I have a variable whose value i would like to use to call an object’s method. like this..

var foo = {
    bar: function() {},
    barr: function() {}
}

now there is a variable whose value can be any of the two method’s names bar and barr
i want to call them with something like

var myvar="bar";
foo.{myVar}();

So I assume you want to call the appropriate function dynamically based on a string. You can do something like this:

var myVar="bar";
foo[myVar]();

Or you can also use eval but this is riskier (prone to injection attack) and slower (don’t do this! :P):

var myVar="bar";
eval('foo.' + myVar + '()');

Since you can access elements of an object via subscript notation, the following will do what you’re looking for:

var myVar="bar";
foo[myVar]();

You can just say:

foo[myVar]();

Since foo is a JavaScript object, this code will reference the member by name contained in the myVar variable.

var foo = {
    bar: function() { alert('bar'); },
    barr: function() { alert('barr'); }
}


var myvar="bar";
foo[myvar](); // alert 'bar'

Use something like: foo[myVar]();

it should be something like this

foo[myvar]();


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   How to create hyperlinks linked to javascript functions in Chrome's console.log?

Similar Posts