dwerty_weird
dwerty_weird

Reputation: 183

How to trigger javascript function, inside a javascript function, by function's argument?

i want to run a function, inside another function dynamically...

let say :

<script>
var x = function(r,s){
    r(s);
}
var a = function(item){
    alert("aA");
}
var b = function(item){
    alert("bB");
}
</script>

is this possible? i take "r" from function x's argument as a function name, and i want to run it.

if r=a, then it will trigger function a()

and if r=b, function b triggered instead...

how could i do that?

Upvotes: 3

Views: 700

Answers (3)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123453

You could simply test r and call each function as needed.

if (r === 'a') {
    a(s);
} else if (r === 'b') {
    b(s);
}

Or, if you have many functions for this or don't always know them all ahead of time, you can organize them in an Object and use bracket operators to treat r as a key name to access them:

var commands = {
    a: function(item){
        alert("aA");
    },

    b: function(item){
        alert("bB");
    }
};

var x = function (r, s) {
    var command = commands[r];

    if (typeof command === 'function') {
        command(s);
    }
};

x('a', 'foo'); // alerts `aA`

Or, even just pass a and b as the arguments themselves with your current definition of x().

x(a, 'foo'); // calls `a` as `r`, passing 'foo' along

Upvotes: 5

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

you mean like:

var x = function(r,s){
    window[r](s);
}
var a = function(item){
    alert("aA");
}
var b = function(item){
    alert("bB:" + item);
}
x('b', 'test');

Upvotes: 3

Adrian
Adrian

Reputation: 1370

By passing the name of the function as the first parameter to x when calling it.

x(a, {}); // alert("aA");
x(b, {}); // alert("bB");

Note that you're passing the reference to the function, not a string. This is because functions in JavaScript are objects and are passed by reference, not by value. So var a = function() {...}; actually means that variable a holds a reference to the function.

Upvotes: 4

Related Questions