So I have the following pseudo Javascript code:
var Class = (function(window, document, $) {
function meth_1()
{
//some code
}
function meth_2()
{
//some code
}
function meth_3()
{
//some code
}
function meth_4()
{
//some code to call other three functions dynamically
}
Class = {
meth_1: meth_1,
meth_2: meth_2,
meth_3: meth_3,
meth_4: meth_4
};
return Class;
})(window, document, jQuery);
In the meth_4 function, I want to call the other 3 functions dynamically by passing the function name as a string. How can I do this?!
In this related StackOverflow question, the answer provides a solution to how this could be done in window scope i.e. window[function_name](). However, I'd like to know how I can do it in my particular circumstance.
Thanks.
EDIT
The answer I selected works ok. You could also do the following:
var Class = (function(window, document, $) {
var meth_func = {
meth_1: function(){/**your code**/},
meth_2: function(){/**your code**/},
meth_3: function(){/**your code**/}
}
function meth_4(func_name)
{
meth_func[func_name]();
}
Class = {
meth_4: meth_4
};
return Class;
})(window, document, jQuery);
This would probably work better if you wanted to make private those three functions being called dynamically.
Since you want to call functions using bracket notation in object scope, not window scope, you can use this instead of window:
function meth_4()
{
this["meth_1"]();
this["meth_2"]();
this["meth_3"]();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With