If you have a function in a variable named x
and you want to call that function, there are several ways you can do that.
function doAlert(msg) {
alert(msg);
}
var x = doAlert;
x("hi");
x.call(this, "hi");
x.apply(this, arrayOfArguments);
See here for more info on .call()
.
See here for more info on .apply()
.
If you have a string that represents a function name and you want to call the corresponding global function with that name, you can do so via the window object.
function doAlert(msg) {
alert(msg);
}
var name = "doAlert";
window[name]("hi");
It is also possible, though not generally recommended, to use eval
:
function doAlert(msg) {
alert(msg);
}
var name = "doAlert";
eval(name + '("hi");');
You asked this question in a comment:
Say i have a function inside functions.js named updateAll that has no parameters... in my php, my json would be $data['function_name'] = 'updateAll'
; which would get encoded with json_encode()... turning that into obj.function_name so could I not just call: obj.function_name(); and have it work?
Here's my answer to that new question:
I'm not sure I fully understand your question, but I'll try to describe various possible aspects of your question.
If function_name
is a variable, you can't use obj.function_name()
. That syntax only works for string constants (not variables).
If you have a method name in a variable, you can always do the same thing as the dot notation by using []
like this: obj[function_name]();
If the function name is in $data['function_name'] = 'updateAll'
and that function name is actually a method on the obj
object, such that what you want to call is `obj.updateAll', then the way you could do that would like this:
obj[$data['function_name']]();
Remember that in Javascript, anywhere that you would use the .x reference for a name that was known ahead of time, you can use the [x] reference for a name that is in a variable.
If (as you posted in a comment), your JSON looked like this:
{"response":"function","msg":"someFunction","attribs":{"id":"1","p_id":"2"}}
and that JSON meant that you wanted to call the function someFunction()
and pass it the parameters in attribs, then there are a couple ways to do that depending upon how you want the arguments passed to the function. If you want the args passed as the attribs object, you'd do it like this:
var data = {"response":"function","msg":"someFunction","attribs":{"id":"1","p_id":"2"}};
if (data.response == "function") {
data.msg(data.attribs);
}
If you wanted the arguments passed as normal parameters with the id parameter first and the p_id parameter second, you'd do it like this:
var data = {"response":"function","msg":"someFunction","attribs":{"id":"1","p_id":"2"}};
if (data.response == "function") {
data.msg(data.attribs.id, data.attribs.p_id);
}