Skip to content Skip to sidebar Skip to footer

Invoke Function With Function Name Passed As String

How to make the alert called for the below snippet? function a(fun) { fun.call(null); } function x() { alert('function called'); } a('x'); Please make sure that editing

Solution 1:

Not many options here. First of all in global window context you can do this:

function a(fun) {this[fun].call(null); // window[fun].call(null);
}

If your functions are in different context above will not work. More flixible approach is to declare methods on the object:

function a(fun) {
    obj[fun].call(null);
}

var obj = {
    x: function() {
        alert("function called");
    }
};

a("x");

Solution 2:

I think if you like eval then you can do like

functiona(fun) {
    eval(fun + "()");
}

but I still suggest that you should do like this. It is used in callback functionality everywhere in many js library.

   function a(fun) {      fun();
}

function x() {
    alert("function called");
}

a(x);

Post a Comment for "Invoke Function With Function Name Passed As String"