103

Can I dynamically call an object method having the method name as a string? I would imagine it like this:

var FooClass = function() {
    this.smile = function() {};
}

var method = "smile";
var foo = new FooClass();

// I want to run smile on the foo instance.
foo.{mysterious code}(); // being executed as foo.smile();
Mikulas Dite
  • 7,202
  • 9
  • 52
  • 94

5 Answers5

226

if the name of the property is stored in a variable, use []

foo[method]();
Karoly Horvath
  • 88,860
  • 11
  • 107
  • 169
  • 2
    it's not working for me using a variable inside a function:const genericResolver = ( table, action , values ) => { return Auth.isAuthenticated() .then(() => { return eval(table).findAll() – stackdave Oct 28 '17 at 14:57
  • If you want to execute a method from another method inside a class, use this['methodName'](). – schlingel Jan 03 '19 at 09:26
  • 3
    Getting this ugly error `Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'FooClass'` anyone else ? – Anand Rockzz Jun 27 '19 at 04:37
34

Properties of objects can be accessed through the array notation:

var method = "smile";
foo[method](); // will execute the method "smile"
Didier Ghys
  • 29,364
  • 9
  • 67
  • 76
6

When we call a function inside an object, we need provide the name of the function as a String.

var obj = {talk: function(){ console.log('Hi') }};

obj['talk'](); //prints "Hi"
obj[talk]()// Does not work
s.n
  • 635
  • 1
  • 9
  • 17
4

method can be call with eval eval("foo." + method + "()"); might not be very good way.

hakovala
  • 185
  • 3
  • Useful in my case where `foo` is `{ fields: [{ id: 1 }] }` and `method` is `fields[0]?.id`, but I had to remove `()` from your proposed answer – Rorrim Jun 09 '20 at 10:50
0

I would like to leave an example here for this. For example; i want to call a dynamically check method while submitting the form.

<form data-before-submit="MyObject.myMethod">
    <button type="submit">Submit</button>
</form>
$('form').on('submit', function(e){

    var beforeSubmit = $(this).attr('data-before-submit');

    if( beforeSubmit ){

       params = beforeSubmit.split(".");
       objectName = params[0];
       methodName = params[1];

       result = window[objectName][methodName]($(this));

       if( result !== true ){
           e.preventDefault();
       }

    }

});

var MyObject = {
    myMethod = function(form){
        console.log('worked');
        return true;
    }
};
ahmeti
  • 255
  • 4
  • 7