Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call javascript object method with a variable

Tags:

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}(); 
like image 853
Achshar Avatar asked Jul 18 '11 18:07

Achshar


People also ask

How do you call a method from an object in JavaScript?

The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.

How do you call an object variable?

Calling an object's method is similar to getting an object's variable. To call an object's method, simply append the method name to an object reference with an intervening '. ' (period), and provide any arguments to the method within enclosing parentheses.

How do you call a function assigned to a variable in JavaScript?

Syntax. Users can follow the below syntax to write the expression for the arrow function. const variable = ( … parameters ) => { // function body } Variable( parameters ); // invoke the arrow function.

Can you call a function in a variable JavaScript?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.


1 Answers

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 + '()'); 
like image 185
pixelfreak Avatar answered Oct 11 '22 05:10

pixelfreak