Mikulas Dite
Mikulas Dite

Reputation: 7941

Javascript dynamically invoke object method from string

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();

Upvotes: 124

Views: 85654

Answers (5)

ahmeti
ahmeti

Reputation: 504

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;
    }
};

Upvotes: 2

s.n
s.n

Reputation: 703

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

Upvotes: 11

hakovala
hakovala

Reputation: 305

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

Upvotes: 5

Didier Ghys
Didier Ghys

Reputation: 30666

Properties of objects can be accessed through the array notation:

var method = "smile";
foo[method](); // will execute the method "smile"

Upvotes: 38

Karoly Horvath
Karoly Horvath

Reputation: 96258

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

foo[method]();

Upvotes: 262

Related Questions