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}();
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.
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.
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.
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.
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 + '()');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With