Javascript: call object method using string only

This code doesn’t work.

var Modal = {
    init: function() {
        console.log("test");
    }
}
var objMethod = "Modal.init";
window[objMethod]();

I saw some answers that it can be called using this but I want to know how it can be called without using the object.

Modal["init"]();

Thank you!

7 thoughts on “Javascript: call object method using string only”

  1. To call a namespaced function, you need to use a multidimensional array. In this case it would be window['Modal']['init'], which can also be expressed by splitting the objMethod string and using array indices:

    var arr = objMethod.split(".");
    window[arr[0]][arr[1]]();
    
    var Modal = {
        init: function() {
            console.log("test");
        }
    }
    var objMethod = "Modal.init";
    var arr = objMethod.split(".");
    window[arr[0]][arr[1]]();
    Reply

Leave a Comment